‘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.












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