Easy tech stuff!

‘indexOf’ or ‘contains’ function for Javascript

Posted: April 1st, 2008 | Author: Nischal Shetty | Filed under: JavaScript | 1 Comment »

The thought of elaborating on the “contains” function for JavaScript occurred to me while I was writing my previous post . From what I know, JavaScript doesn’t seem to have a function to allow the user to check if a particular letter exists in the given data.

But, it does have an indexOf() function that might just do the trick :)

All you need to do is check whether the return value is -1 or not. A return value of -1 implies that the specific letter is not present in the given data.

A simple example below will make things clear:

function checkIndexOf()
{
var a = “hello”;

alert(a.indexOf(‘l’));
alert(a.indexOf(‘E’));
alert(a.indexOf(’0′));

}

The output is as follows:

2 // which implies that the letter ‘l’ is present in position 2.

-1 //which implies that the letter ‘E’ is not present.(JavaScript is case sensitive)

-1 //which implies that the number 0 is not present.

http://www.techtamasha.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/google_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/twitter_48.png

One Comment on “‘indexOf’ or ‘contains’ function for Javascript”

  1. 1 Olga said at 2:59 pm on December 10th, 2009:

    It’s great idea! The only thing that helped me in my Selenium tests when ‘contains’ refused to work!

    Thanks a lot:)


Leave a Reply