Home and Learn: Javascript Programming Course


Javascript Strings - indexOf

The indexOf method tells you if a string of text contains a particular character, the @ sign in an email address for example. It won't check every occurrence of the character, but just the first one. If the character can't be found then IndexOf returns a value of -1 (minus 1). If the character is found then the value returned is the position in the string (6th character, for example).

To test out indexOf (capital letter "O"), change your code to this (or create a new web page):

var email = "meme@meme.com";
var at_sign = email.indexOf('@');
document.write( at_sign );

This code sets up a variable to hold an email address. We want to check if the email address contains an @ sign. indexOf is used like this:

var at_sign = email.indexOf('@');

Again, you start on the right of an equal sign, and with the variable you want to check. After a dot, you type IndexOf. In between the round brackets of indexOf you need to type the character or characters you are checking for. The character or characters need to go between quotation marks. (You can check for more than one character, .com, for example. In which case the number returned will be for the first character of your string.)

If you run the script above, you'll find that Javascript returns a value of 4. You might think that the @ sign in our email address is at position 5. However, Javascript starts the count from 0, which is why the answer is 4.

Now delete the @ sign from the email address on the first line of the code. Run the script again and you should find a value of -1 is written to the page.

You can use this information in an IF Statement. Like this:

if ( at_sign == -1 ) {

document.write( "no @ sign in email address" );

}

else {

document.write("email address contains @ sign");

}

The code above just checks the at_sign variable for a value of -1 and takes action accordingly. Add it to your own code and test it out. Put the @ sign back in and rerun your code.

In the next part, you'll learn about a Javascript string method called charAt.

Back to the Home Page

 


Email us: enquiry at homeandlearn.co.uk