How can I check if one string contains another substring in JavaScript?
5
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.

Update: It seems that I have another problem.

When I use the ".indexof" method, Firefox refuses to start the JavaScript code (this is for an extension).

My code is:

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.
improve this question | comment
Krystina Shields Created at: 2013-11-13 17:07:42 UTC By Krystina Shields
Probably worth pointing out that you're using indexof above and not indexOf - Gaston Gutkowski
Yeah thanks, it also didn't help. I finally discovered the Error console, it helped also. - Ms. Crystel Olson
As this is now a reference resource for indexOf();, it's worth mentioning that, on a string, .indexOf() has near universal browser support, but on an array, .indexOf() is only supported in IE9+. - Kayleigh Beer
Another problem with the code above is that test will be null for any link that doesn't have class explicitly specified. So the loop will almost certainly crash with a TypeError at some point, effectively trying to call null.indexOf(...) - Miss Berniece Prohaska
possible duplicate of array.contains(obj) in JavaScript - Lucinda Grant
19 Answers
0
Since the question is pretty popular, I thought I could add a little modern flavor to the code.

var allLinks = content.document.getElementsByTagName("a"),
    il = allLinks.length,
    i = 0,
    test, 
    alrt;

while (i < il) {
  elm = allLinks[i++],
  test = elm.getAttribute("class");

  if (test.indexOf("title") > -1) console.log(elm), foundLinks++;   
}
alrt = foundLinks === 0 ? "No title class found" : "Found " + foundLinks + " title class";
console.log(alrt);


Btw the correct answer is misspelling indexOf or the non-standard String.contains.
Loading an external library (especially if the code is written in pure javascript) or messing with String.prototype or using a regex is a little over kill.
0
A contains method has been added to Strings in Javascript 1.8.6:

"potato".contains("to");
> true


Of course, we will have to wait decades for mainstream support :P

(source)
0
indexOf returns the position of the string in the other string. If not found, it will return -1:

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

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

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };


Note: see the comments below for a valid argument for not using this. My advice: use your own judgement.
0
The problem with your code is that JavaScript is case sensitive. Your method call

indexof()


should actually be

indexOf()


Try fixing it and see if that helps:

if (test.indexOf("title") !=-1) {
    alert(elm);
    foundLinks++;
}

0
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 regular expression 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).
0
var index = haystack.indexOf(needle);

0
You can use jQuery's ':contains' selector.

$("div:contains('John')")


check it here: http://api.jquery.com/contains-selector/
0
This piece of code should work well:

var str="This is testing for javascript search !!!";
if(str.search("for") != -1) {
   //logic
} 

0
String.contains() introduced in JavaScript 1.8.6


  Determines whether one string may be found within another string, 
  returning true or false as appropriate.


Syntax

var contained = str.contains(searchString [, position]);  


Parameters

searchString


A string to be searched for within this string.

position


The position in this string at which to begin searching for searchString defaults to 0.  

Example

var str = "To be, or not to be, that is the question.";

console.log(str.contains("To be"));    // true
console.log(str.contains("question")); // true
console.log(str.contains("To be", 1)); // false  


Note

Only supported in Firefox from version 19. 
0
This just worked for me. It selects for strings that do not contain the term "Deleted:"

if (eventString.indexOf("Deleted:") == -1)

0
A common way to write a contains method in JS is:

if (!String.prototype.contains) {
    String.prototype.contains = function (arg) {
        return !!~this.indexOf(arg);
    };
}


The bitwise negation operator (~) is used to turn -1 into 0 (falsey), and all other values will be non-zero (truthy).

The double boolean negation operators are used to cast the number into a boolean.
0
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

0
Another option of doing this is:

You can use the match function, that is, something like:

x = "teststring";

if (x.match("test")) {
     // Code
}

0
jsFiddle Demo

Your code works, however you have misspelled the API function.  As a result of the misspelling, you were getting the error "Uncaught TypeError: Object title has no method 'indexof'" which was preventing the execution of the rest of your script.

Many functions in javascript use the "camel case" naming convention. This dictates that the first letter be lower case, and the first letter of every other word be capitalized. Thus, by convention, you were looking for .indexOfMDN.

indexOf is going to return an index to the matched substring. The index will correlate to where the substring starts. If there is no match, a -1 is returned. Here is a simple demo of that concept:

var str = "Hello World";// For example, lets search this string,
var term = "World";// for the term "World",
var index = str.indexOf(term);// and get its index.
if(index != -1){// If the index is not -1 then the term was matched in the string,
 alert(index);// and we can do some work based on that logic. (6 is alerted)
}

0
indexOf didn't work for me in Internet Explorer 8, and so I used jQuery's inArray() method:

$.inArray("search_string", in_array)

0
JavaScript code to use contain method in an array

 <html>
<head>
<h2>Use of contains() method</h2>
<script>
Array.prototype.contains = function (element) {
for (var i = 0; i < this.length; i++) {
if (this[i] == element) {
return true;
}
}
return false;
}
arr1 = ["Rose", "India", "Technologies"];
document.write("The condition is "+arr1.contains("India")+"<br>");
</script>
</head>
<b>[If the specified element is present in the array, it returns true otherwise 
returns false.]</b>
</html>


In the given code the contain method determines whether the specified element is present in the array or not. If the specified element is present in the array, it returns true otherwise it returns false.
0
Use regular expression

RegExp.test(string)
0
Since there is a complaint about using the prototype, and since using indexOf makes your code less readable, and since regexp is overkill:

function stringContains(inputString, stringToFind) 
{
    return (inputString.indexOf(stringToFind) != -1);
}


That is the compromise I ended up going for.
Your Answer