ava script tutorial - a new approach by Ken J Ward

Java Script Tutorial - Finding a string in a bigger string

indexOf()


We can find if a string is in a bigger string as follows:

Bigstring.indexOf(smallstring);

For example click on these to find the answers:

'abcdefgh'.indexOf('cde');

In my browser, the alert says the value is 2. That is the small string begins with the third character!

'abcdefgh'.indexOf('xyz');

Here I get the answer -1. The small string does not exist in the big string.

So using indexOf() we can find out the position of a smaller string in a bigger string (with 0 as the first position), or if it doesn't exist we get -1.

We can use this in the following example.

Enter a valid e-mail address and then an invalid one in the box below and press the button.

If the box contains an '@' then the alert says the e-mail appears valid, otherwise, it says it appears invalid.

Here is the the code:


function valid()

{

if(document.form2.text2.value.indexOf('@')!='-1')

/* We are saying that if the box doesn't contain a minus one (-1), that is, the @ sign is found, then we will say the e-mail appears valid.*/

{

alert('Email appears valid');

}

else

{

alert('Email appears invalid');

}

}


Of course, it doesn't mean that the e-mail is valid! If you put only an @ character or two or three, it will still say the code appears valid! But we have made the first step in checking that an e-mail address is valid!

Did you know that indexOf() has a little friend? His (or her) name in lastIndexOf(). This function is much like its little friend. So when we look at this function, we will also look at one or two useful tricks!

Next: lastIndexOf()

 

[If you need to learn more about HTML visit the HTML Tutorial]

I am always pleased to hear from you.
Send your comments to