Javascript Strings - charAt

Five part section: 1 2 3 4 5

In the previous section, you used indexOf to get the position of one string of text inside another. But if you want the character returned rather than its position number then you can use the Javascript string method charAt. Like this:

if ( at_sign == -1 ) {

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

}
else {

var character = email.charAt( at_sign );
document.write( character );

}

The first line of the else part of the IF Statement is now this:

var character = email.charAt( at_sign );

After the email variable we have chartAt. In between its round brackets you need a number. The number is the position in the string you want to grab. Our at_sign variable contains the number 4, which is where the @ sign is in the email address. This character will then be stored in the variable we've called character.

If you want the keyboard code of the character you've just grabbed then you can use charCodeAt instead of charAt:

var character = email.charCodeAt( at_sign );

The character variable will now contain the keyboard code 64 on a UK keyboard.

<

In the next lesson, you'll see how to grab one or more characters from a string of text.