views:

44317

answers:

7

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.

Edit : thanks for all the answers :) however it seems that I have another problem :(

when I use the ".indexof" method, Firefox refuses to start the javascript (this is for an extension).

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");
  }

Firefox doesn't display an alert box. This works if I get rid of the .indexof() method. I already tried something like if(test=="title")... but it didn't work.

+71  A: 
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.

https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Objects/String/indexOf

Fabien Ménager
+2  A: 
var index = haystack.indexOf(needle);
pixeline
A: 

Use regular expression

RegExp.test(string)

rahul
Using a regex is a little overhead to only check for the presence of a substring.
Fabian Vilers
+5  A: 

Javascript is case sensitive

indexOf()

not

indexof()
Victor
A: 

You need to call indexOf with a capital "O" as mentioned. It should also be noted, that in JavaScript class is a reserved word, you need to use className to get this data attribute. The reason it's probably failing is because it's returning a null value. You can do the following to get your class value...

var test = elm.getAttribute("className");
//or
var test = elm.className
MillsJROSS
+17  A: 

I know your question is already answered, but I thought this might be helpful too.

You can easily add a contains method to String with this statement:

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };
Avi Flax
+3  A: 

Hello,

You could use the javascript search() method

Syntax is: string.search(regexp)

it returns the position of the match, or -1 if no match is found.

See examples there: jsref_search

You don't need a complicated Regexp syntax, if you are not familiar with them a simple st.search("title") will do. If you want your test to be case insensitive, then you should do st.search(/title/i).

Tardis
This seems like it would be slower than the indexOf function because it would have to parse the RegEx. However, if you want something case insensitive, your way would be the way to go (I think), although that was not what was asked. Even though it wasn't asked, I'm voting this up _just_ _because_ of the case insensitive option.
PiPeep