‘indexOf’ or ‘contains’ function for Javascript

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.

2 comments

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

    Thanks a lot:)

  2. What a joy to find such clear tihnking. Thanks for posting!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>