IndexOf

14 Jan

The indexOf finds the location of a set of characters inside a string and tells you where the substring starts.

var the_word = “monkey”; //Let’s start with the word “monkey.”

var location_of_m = the_word.indexOf(“m”); // The location_of_m will be “0,”

var location_of_key = the_word.indexOf(“key”); // The location_of_key is “3”

var cheeky = the_word.indexOf(“q”); // The cheeky is “-1” coz there’s no letter “q” in “monkey.”

A more realistic use of indexOf is:

var the_email = prompt(“What’s your email address?”, “”);

var the_at_is_at = the_email.indexOf(“@”);

if (the_at_is_at == -1)
{
alert(“You loser, email addresses must have @ signs in them.”);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: