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
115  
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
13  
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

19 Answers

up vote 2434 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
93  
you should be using !== fyi. –  Steve May 26 '11 at 19:29
115  
> would save a byte :) –  Steve Jun 6 '11 at 22:39
255  
@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
161  
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
710  
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 13 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
58  
Don't modify objects you don't own. nczonline.net/blog/2010/03/02/… –  zachleat Feb 17 '11 at 19:59
22  
@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
22  
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
28  
if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; } –  Pavel Hodek Jun 7 '11 at 15:24
22  
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 8 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
9  
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
 
Always jQuery... Hooray!!! –  Qeremy Sep 5 at 12:14
3  
That searches DOM elements though… –  sam Sep 26 at 21:03
 
dom parsing has nothing to do with the question –  oligofren Nov 1 at 12:06
 
yeah, how did this get 31 up votes? it has nothing to do with the question asked .... it's cool and interesting and something I didn't know, but is quite unrelated –  Landon 2 days ago

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

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
1  
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
1  
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

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

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
4  
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
4  
@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
2  
!!~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

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

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

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)
}
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
35  
Using a regex is a little overhead to only check for the presence of a substring. –  Fabian Vilers Nov 24 '09 at 13:55

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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.