#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    21
    Rep Power
    0

    Post Get the first character of a string and use in if statement


    Hi,

    I need to check if the first character in a string, seq, is R or K.

    WHAT I WANT TO DO IN CODE (KIND OF):
    Code:
    If (first char of seq == "R" || first char of seq == "K"){
    EXECUTE CODE HERE
    }
    What shall I replace first char of seq with?

    Thanks,
    Daniel
  2. #2
  3. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,041
    Rep Power
    119
    You would do it like so:
    Code:
    <script>
    var letter;
    function findLetter()
    {
    var someString = "Round and round, the merry go round, we go!"; // define sentence here
    someString = someString.toLowerCase().substr(0,1);
     if(someString == "r") {
      letter = "R";
     }
     else if(someString == "k") {
      letter = "K";
     }
      alert("\"" +letter + "\" Was Found At The Beginning of Your Sentence");
    }
    window.onload = function(){
     findLetter();
    }
    </script>
  4. #3
  5. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,122
    Rep Power
    4258
    You could also use "charAt(0)" instead of "substr(0,1)".

    Loone, I'm curious, did you have a particular reason for making "letter" a global variable?
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).
  6. #4
  7. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,041
    Rep Power
    119
    Originally Posted by Kravvitz
    Loone, I'm curious, did you have a particular reason for making "letter" a global variable?
    Yeah; thought it may need to be accessible else where.

IMN logo majestic logo threadwatch logo seochat tools logo