Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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:

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.

share|improve this question
86  
Probably worth pointing out that you're using indexof above and not indexOf – tschaible Nov 24 '09 at 13:33
5  
Yeah thanks, it also didn't help. I finally discovered the Error console, it helped also. – gramm Nov 24 '09 at 14:34
8  
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+. – user568458 Nov 17 '12 at 19:58
2  
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(...) – ytpete Apr 24 at 18:58
possible duplicate of array.contains(obj) in JavaScript – Michel Jun 27 at 16:09

15 Answers

up vote 2015 down vote accepted

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);
share|improve this answer
62  
you should be using !== fyi. – Steve May 26 '11 at 19:29
80  
> would save a byte :) – Steve Jun 6 '11 at 22:39
200  
@Steve indexOf always returns a number so there’s no need to use !==. If you want to save bytes, you could use ~'foo'.indexOf('oo') which returns a truthy value if the substring is found, and a falsy value (0) if it isn’t. – Mathias Bynens Jul 7 '11 at 11:00
132  
For the curious: in two's compliment systems, -1 is represented in binary as all 1s (1111 1111 1111 1111 1111 1111 1111 1111 for 32 bit). The bitwise inverse (~) of this is all zeros, or just zero, and therefore falsy. That's why the squiggle trick works, and it is pretty bad-ass if I must say so myself. – Adam Tolley Sep 14 '11 at 21:36
529  
Writing code that is unreadable because it's full of tricks isn't "bad ass" so much as just "bad". – boxed Dec 23 '11 at 8:45
show 14 more comments

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.

share|improve this answer
48  
Don't modify objects you don't own. nczonline.net/blog/2010/03/02/… – zachleat Feb 17 '11 at 19:59
17  
@zachleat, that understandable in practice. But "foobar".contains("bar") would be a really useful exception to the rule. – nathan.f77 Feb 22 '11 at 9:50
20  
Eh, my preference would be to adapt my mental model to fit JavaScript and just use indexOf. It will make the code easier to understand for the next JavaScripter that comes along and has to read it. – zachleat Mar 4 '11 at 16:03
20  
if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; } – Pavel Hodek Jun 7 '11 at 15:24
17  
I this it is preferrable to use this function if you are going to be using this kind of indexOf's frequently. @zachleat, I would disagree that using indexOf is more readable than contains. Contains describes what is happening, where to some indexOf() != -1 may not be so transparent. But to each their own, as long as you're consistant. – smdrager Jul 11 '11 at 14:03
show 5 more comments

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++;
}
share|improve this answer

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

share|improve this answer
4  
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 Jun 3 '10 at 22:21
8  
I haven't run a benchmark, but would str.toLowerCase().indexOf(searchstr.toLowerCase()) be much more efficient for case-insensitive search? – Tim S. Jan 31 '12 at 10:29
With a benchmark and it turns out search is more efficient for case insensitive searching. jsperf.com/string-compare-perf-test But it could be tricky to use regex search as you need to escape some characters. – misaxi Jul 9 at 6:13
var index = haystack.indexOf(needle);
share|improve this answer

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

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

check it here: http://api.jquery.com/contains-selector/

share|improve this answer

This piece of code should work well:

var str="This is testing for javascript search !!!";
if(str.search("for") != -1) {
   //logic
} 
share|improve this answer
can you explain a bit more extensively your answer? tnx – Daniele B May 29 '12 at 23:27
it searches for the passed character or a word if it is found then search returns a integer value which is the position of word in the entire string. If a word or a character is not found then it search function returns -1. – vaibhav Jun 1 '12 at 4:43

This just worked for me. It selects for strings that do not contain the term "Deleted:"

if (eventString.indexOf("Deleted:") == -1)
share|improve this answer

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
share|improve this answer
1  
Your first approach is not correct: elm.getAttribute("class") == elm.className != elm.getAttribute("className") – SebastianG Mar 12 at 14:22

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)

share|improve this answer
because I was used to "contains" in other languages and just implemented my feature with it, I just ran into the error. So, short feedback about the support. Firefox 19 - OSX => OK, Firefox 19 - Windows => NOK, Chrome - OSX,Windows => NOK – phammer Feb 21 at 10:18
Like this? String.prototype.contains = function (segment) { return this.indexOf(segment) !== -1; }; (BTW: Doing things on the prototype is bad) – Nijikokun May 10 at 2:50

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.

share|improve this answer
3  
What's the advantage of !!~ over >-1? – alex Dec 12 '12 at 4:29
@alex, There isn't any particular advantage other than not relying on magic numbers. Use what you feel comfortable with. – zzzzBov Dec 12 '12 at 4:59
+1 for Bitwise. Awesome – MacroMan Apr 9 at 14:53
3  
@zzzzBov !~~ is just as much relying on the magic number -1, and the fact that its bitwise representation is the complement of 0. – Martijn May 14 at 9:33
1  
!!~this.indexOf(arg); isn't easy understandable and not as clear in the context as it must be. It also relays on the fact ~-1 is 0, agreed with @Martijn. Also it's slower than simple comparison with -1. But clearness is the main factor. – Nick May 20 at 15:40
show 1 more comment

Another option of doing this is:

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

x = "teststring";

if (x.match("test")) {
     // Code
}
share|improve this answer

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

$.inArray("search_string", in_array)
share|improve this answer

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.

share|improve this answer

Use regular expression

RegExp.test(string)

share|improve this answer
30  
Using a regex is a little overhead to only check for the presence of a substring. – Fabian Vilers Nov 24 '09 at 13:55

protected by Sean Vieira Nov 2 '12 at 12:31

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.

Not the answer you're looking for? Browse other questions tagged or ask your own question.