Saturday, September 8, 2012

How can I check if one string contains another substring in JavaScript? JavaScript: string contains

Q. How can I check if one string contains another substring in JavaScript?








Usually I would expect a String.contains() method, but there doesn't seem to be one.

My code is:

var allLinks = content.document.getElementsByTagName("a");

for (var i=0, il=allLinks.length; i<il; i++) {
   
   elm = allLinks[i];
   var test = elm.getAttribute("class");
   if (test.indexof("title") !=-1) {
   alert(elm);
   foundLinks++;

}
}

if (foundLinks === 0) {
   alert("No title class found");
}
else {
   alert("Found " + foundLinks + " title class");
}



Solution :



var s = "foo";
alert(s.indexOf("oo") != -1);

indexOf returns the position of the string in the other string. If not found, it will return -1.





Cheers !
Hope you got the Ans !
still having probs ? let me know by comments !

Know More About :
PHP Freelancing India


Reactions:

0 comments:

Post a Comment

Any Questions or Suggestions ?

About

Professional & Experienced Freelance Developer From India, Technologist, Software Engineer, internet marketer and Open Sources Developer with experience in Finance, Telecoms and the Media. Contact Me for freelancing projects.

Enter your email address:

Delivered by FeedBurner

PHP Freelancer India - Google+