Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Usually, I would expect a String.contains() method, but there doesn't seem to be one. What is the reasonable way to check for this?

share|improve this question
13  
It's easy with the indexOf method, you can see a tutorial of indexOf and substring here: dreamsyssoft.com/javascript-shell-scripting/… – Triton Man Mar 30 '15 at 17:53
5  
possible duplicate of JQuery string contains check – Saswat Aug 18 '15 at 11:14
5  
you can see speed of r.indexOf(s) !== -1; fastest than others. hayageek.com/javascript-string-contains – Sherali Turdiyev Oct 1 '15 at 5:37
3  
Here a benchmark for the most common ways to check if a string is in a string: jsben.ch/#/o6KmH – EscapeNetscape Oct 26 at 9:38
1  
Video covering the best of the options below in < 5 minutes, here: youtube.com/watch?v=KENPi0xTgcE – ssmith Dec 14 at 16:19

40 Answers 40

up vote 7956 down vote accepted

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

var string = "foo",
    substring = "oo";
console.log(string.indexOf(substring) !== -1);

Edit:

Since the original answer from 2009 is outdated, here a list of other possibilities from this thread:

1. indexOf - (see above)

2. (ES6) includes - go to answer, or this answer

var string = "foo",
    substring = "oo";
string.includes(substring);

3. search - go to answer

var string = "foo",
    expr= "/oo/";
string.search(expr);

4. lodash includes - go to answer

var string = "foo",
    substring = "oo";
_.includes(string, substring);

5. RegExp - go to answer

var string = "foo",
    expr= "/oo/";
expr.test(string);

6. Match - go to answer

var string = "foo",
    expr= "/oo/";
string.match(expr);

Performance tests (http://jsben.ch/#/RVYk7) are showing that indexOf might be the best choice, if it comes to a point where speed matters.

share|improve this answer
692  
@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
529  
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
31  
@SebNilsson You forgot to include the ~ operator that I suggested in my comment. ~'hello'.indexOf('h'); // -1, which is truthy, but ~'hello'.indexOf('x'); // 0, which is falsy. – Mathias Bynens Feb 8 '12 at 8:05
24  
@pramodc84 that link refers to the Array object indexOf method not to the String object method – gion_13 Apr 26 '12 at 13:26
44  
@NicolasBarbulesco I am confident that all of the people who look at my code will know that [["\t\n 987654321e-400"]] === 0 is false. I am much less confident that everyone who looks at my code will know that [["\t\n 987654321e-432"]] == 0 is true. – kybernetikos Dec 11 '13 at 15:48

String.prototype.indexOf() or String.prototype.search()?!

As others have already mentioned, JavaScript strings have both an indexOf and search method.

The key difference between both, is that indexOf is for plain substrings only, whereas search also supports regular expressions. Of course, an upside of using indexOf is that it's faster.

See also In JavaScript, what is the difference between indexOf() and search()?.

Implementing your own String.prototype.contains() method

If you want to add your own contains method to every string, the best way to do it would be @zzzzBov's approach:

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

You would use it like this:

'Hello World'.contains('orl');

Implementing a custom utility library

It is generally frowned upon to add your own custom methods to standard objects in JavaScript, for example, because it might break forward compatibility.

If you really want your own contains method and/or other custom string methods, it's better to create your own utility library and add your custom string methods to that library:

var helper = {};

helper.string = {
    contains : function (haystack, needle) {
        return !!~haystack.indexOf(needle);
    },
    ...
};

You would use it like this:

helper.string.contains('Hello World', 'orl');

Using a third-party utility library

If you don't want to create your own custom helper library, there is - of course - always the option of using a third-party utility library. As mentioned by @nachtigall, the most popular ones are Lodash and Underscore.js.

In Lodash, you could use _.includes(), which you use like this:

_.includes('Hello World', 'orl');

In Underscore.js, you could use _.str.include(), which you use like this :

_.str.include('Hello World', 'orl');
share|improve this answer

One more function, search:

var str = "Stack Overflow";
var n = str.search("Overflow");
if (n != -1)
    alert('String exists')
share|improve this answer
1  
search is for regular expressions – Gothdo Dec 11 '15 at 18:30

A common way to write a contains method in JavaScript 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
12  
What's the advantage of !!~ over >-1? – alex Dec 12 '12 at 4:29
2  
@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
11  
@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 '13 at 9:33
7  
!!~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. – babinik May 20 '13 at 15:40
1  
@Nick, I never claimed that it was a good way, I just said it was a common way. As far as clarity is concerned, I feel that it's a reasonable way to save a couple bytes for a library, but I tend to use foo.indexOf('bar') > -1 – zzzzBov May 20 '13 at 15:43

With ECMAScript 2015, we can use includes()

let s = "foo";
console.log(s.includes("oo"));
share|improve this answer
    
This is just repeating some of the existing answers. – Pang Oct 8 at 3:55

String.prototype.includes() was introduced in ES6.

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

Syntax

var contained = str.includes(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.includes("To be"));    // true
console.log(str.includes("question")); // true
console.log(str.includes("To be", 1)); // false  

Note

This may require ES6 shim in older browsers.

share|improve this answer
3  
Apparently it's includes, not contains – Sam Apr 28 '15 at 5:36
1  
FWIW the linked MDN page has a simple shim/polyfill: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Salman Abbas Sep 13 at 19:39

In ES5

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

In ES6 there are three new methods: includes(), startsWith(), endsWith().

var msg = "Hello world!";

console.log(msg.startsWith("Hello"));       // true
console.log(msg.endsWith("!"));             // true
console.log(msg.includes("o"));             // true

console.log(msg.startsWith("o", 4));        // true
console.log(msg.endsWith("o", 8));          // true
console.log(msg.includes("o", 8));          // false

share|improve this answer
2  
Thanks for including startsWith and endsWith – v010dya May 31 at 6:01
    
support w3schools.com/jsref/jsref_endswith.asp – zloctb Aug 2 at 3:59

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.

Alternatively:

if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }
share|improve this answer
270  
Don't modify objects you don't own. nczonline.net/blog/2010/03/02/… – zachleat Feb 17 '11 at 19:59
71  
@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
65  
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
73  
if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; } – Pavel Hodek Jun 7 '11 at 15:24
54  
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

There are multiple ways to do this. But most of the time, you will be fine using the indexOf() method. indexOf() returns the position of the string passed to it as argument and -1 if the string on which it was called doesn't contain the argument string.

var str = "A cat and a dog";
str.indexOf("cat"); // returns 2
str.indexOf("panda"); // returns -1
share|improve this answer

ES6 contains String.prototype.includes.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

share|improve this answer
    
@MikeMüller The question was why there is not a String.contains method, and the answer is that there is one in ES6. The link is provided merely as additional documentation. – torazaburo Jan 4 at 5:35
    
There was a contains in pre-release ES6 but it was changed to includes. Your contains method link redirects to the includes method here: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Here's the proof it was renamed: bugzilla.mozilla.org/show_bug.cgi?id=1102219 – Jeremy Odekirk Jun 2 at 19:08

Example

var a  = "Test String";

if(a.search("ring")!=-1){
     //exist 
} else {
     //not found 
}
share|improve this answer

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

You can also do something like this

var snipers = " Vasily Zaytsev, Simo Hayha, Chris Kyle";
var me = "Josip";

function printSniperStatus (person) {
    if (aContainsB(snipers, person)) {
        console.log(person + " is a sniper.");
    } else {
        console.log(person + " is NOT a sniper.");
    }
}

// Outputs: "Josip is NOT a sniper."
printSniperStatus(me);
share|improve this answer
    
Is aContainsB a standard javascript function? I found it to be a custom function here: adripofjavascript.com/blog/drips/…. The function itself is: function aContainsB (a, b) { return a.indexOf(b) >= 0; }. – Dov Miller Sep 15 at 12:24

You can use indexOf which returns the position of the string. If not found, it will return -1. So if the method returns -1 string doesn't exist

var string = "This is a test string",
substring = "test";
if(string.indexOf(substring) >= 0)
  //substring exist
else
  //substring does not exist
share|improve this answer

Instead of using code snippets found here and there on the web, you can also use a well-tested and documented library. Two Options I would recommend:


1st option: Use Lodash: It has an includes method:

_.includes('foobar', 'ob');
// → true

Lodash is the most popular javascript library dependency for npm and has loads of handy javascript utility methods. So for many projects you would want this anyway ;-)


2nd option: Or use Underscore.string: It has an include method:

_.str.include('foobar', 'ob');
// → true

Here is the description of Underscore.string, it just adds 9kb but gives you all the advantages a well-tested and documented library has over copy'n'paste code snippets:

Underscore.string is JavaScript library for comfortable manipulation with strings, extension for Underscore.js inspired by Prototype.js, Right.js, Underscore and beautiful Ruby language.

Underscore.string provides you several useful functions: capitalize, clean, includes, count, escapeHTML, unescapeHTML, insert, splice, startsWith, endsWith, titleize, trim, truncate and so on.

Note well, Underscore.string is influenced by Underscore.js but can be used without it.


Last not Least: With JavaScript version ES6 comes an built-in includes method:

'foobar'.includes('ob');
// → true

Most modern browsers already support it, have an eye on the ES6 compatibility table.

share|improve this answer
4  
I don't see how figuring out the underscore method is in any way superior to simply using the well-documented core functionality provided in javascript, as illustrated here. To the type of coder that copies and pastes code, your sample code would be no more or less a "copy'n'paste code snippet" than any other solution provided here, except, it would require the addition of a library. Adding libraries simply to accomplish tasks that are just as easily done using the native language, regardless of library size, is bad advice. -1 from me for knee-jerk library use on a old question. – Chris Baker Jan 12 '14 at 5:37
6  
If you are using Underscore already, you should probably use this approach anyway, as it makes your code more readable and more self-explanatory to people not that familiar with JavaScript... Remember that Stack Overflow answers are useful for more people than just the OP. – whirlwin Jan 4 '15 at 22:30
    
_.str.include seems to be gone in underscore – pixelearth Apr 24 at 17:13
    
@pixelearth It's not in underscore, but underscore.string. The link under include in the answer points to the description ;) If you use underscore currently, lodash might be a better solution anyway as it comes with its own includes method and even more very useful helper functions. – nachtigall Apr 25 at 12:56

If you were looking for an alternative to write the ugly -1 check, you prepend a ~ tilde instead.

if (~haystack.indexOf('needle')) alert('found');

Joe Zimmerman - you'll see that using ~ on -1 converts it to 0. The number 0 is a falsey value, meaning that it will evaluate to false when converted to a Boolean. That might not seem like a big insight at first, but remember functions like indexOf will return -1 when the query is not found. This means that instead of writing something similar to this:

if (someStr.indexOf("a") >= 0) {
  // Found it
} else  {
  // Not Found
}

You can now have fewer characters in your code so you can write it like this:

if (~someStr.indexOf("a")) {
  // Found it
} else  {
  // Not Found
}

More details here

share|improve this answer
    
I don't get why this isn't the right answer. Just because of the obscurity of using ~ (which I'd never heard of either yet). – Jesse Mar 19 at 21:46
    
I'd rather have "more characters in my code" than "confusing magic in my code" – Mr Spoon Oct 6 at 12:26
1  
Yes, now I would rather recommend polyfill the ES6 standard includes() by following this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Christian Landgren Oct 10 at 9:32

Try this:

if ('Hello, World!'.indexOf('orl') !== -1)
    alert("The string 'Hello World' contains the substring 'orl'!");
else
    alert("The string 'Hello World' does not contain the substring 'orl'!");

Here is an example: jsfiddle

share|improve this answer

You can use jQuery's :contains selector.

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

Check it here: contains-selector

share|improve this answer
23  
That searches DOM elements though… – sam Sep 26 '13 at 21:03
18  
dom parsing has nothing to do with the question – oligofren Nov 1 '13 at 12:06
15  
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 Nov 13 '13 at 0:13
3  
it's loosely related... if the string you're searching through happens to be located within a DOM element, jQuery's :contains selector can be used. – Joshua Burns Nov 20 '13 at 20:50

I know that best way is str.indexOf(s) !== -1; http://hayageek.com/javascript-string-contains/

I suggest another way(str.replace(s1, "") !== str):

var str = "Hello World!", s1 = "ello", s2 = "elloo";
alert(str.replace(s1, "") !== str);
alert(str.replace(s2, "") !== str);

share|improve this answer

Simple workaround

if (!String.prototype.contains) {
  String.prototype.contains= function() {
    return String.prototype.indexOf.apply(this, arguments) !== -1;
  };
}

you can use in the following way

"hello".contains("he") // true
"hello world".contains("lo w")//true
"hello world".contains("lo wa")//false
"hello world".contains(" ")//true
"hello world".contains("  ")//false

MDN reference

share|improve this answer
    

To collect some kind of valid solutions:

var stringVariable = "some text";
var findString = "text";

//using `indexOf()`
var containResult = stringVariable.indexOf(findString) != -1;
console.log(containResult);

//using `lastIndexOf()`
var containResult = stringVariable.lastIndexOf(findString) != -1;
console.log(containResult);

//using `search()`
var containResult = stringVariable.search(findString) != -1;
console.log(containResult);
     
//using `split()`
var containResult = stringVariable.split(findString)[0] != stringVariable;
console.log(containResult);

share|improve this answer
    
I don't see any point in using lastIndexOf if you only want to check if a string contains a substring. search method is only for regular expressions. split method makes it only more complicated. – Gothdo Dec 11 '15 at 18:29
    
As you said a valid solution is not the best solution, and here are just some valid solutions ;). – shA.t Dec 12 '15 at 4:42

Update for 2015: string.includes has been added to JavaScript's next version, ES6:

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

Note you may need to load es6-shim or similar to get this working on older browsers.

require('es6-shim')
share|improve this answer
4  
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 – Patrick Hammer Feb 21 '13 at 10:18
4  
Like this? String.prototype.contains = function (segment) { return this.indexOf(segment) !== -1; }; (BTW: Doing things on the prototype is bad) – Nijikokun May 10 '13 at 2:50
4  
It is not support in chrome.....:( – Krunal Patel Jun 24 '14 at 11:15
5  
@Norris It's in ES6. Load ES6 shim. You can use it now. – mikemaccana Jan 15 '15 at 14:56
7  
.contains() and .includes() are both experimental, re: non-standard. I would not recommend their use in production systems. I'd stick with .indexOf() for now. – Mike S. Mar 22 '15 at 13:47

JavaScript

 var str = "My big string contain apples and oranges";
 var n = str.indexOf("apples"); 
 alert(n); //will alert 22, -1 if not found

jQuery

  <p>My big string contain apples and oranges</p>
  alert($("p:contains(apples)")[0] != undefined); //will alert true if found
share|improve this answer

There is a sleek and better way to do this and it is using the (BitWise NOT) operator.

if(~"John".indexOf("J")) {
  alert("Found")
}
else {
  alert("Not Found");
}

The Bitwise Not converts "x" into -(x + 1) so, if the x turns out -1 from indexOf method.then it will be converted into -( -1 + 1) = -0 which is a falsy value .

share|improve this answer
    
stackoverflow.com/a/23598591/497418 and stackoverflow.com/a/12399125/497418 predate this answer, consider deleting it in favor of the later community wiki answer. – zzzzBov May 2 at 20:28

This is a function to check if a substring is existing in a string or not:

function isStringMatch(str, str_to_match) {
    return (str.indexOf(str_to_match) > -1);
}
share|improve this answer
3  
Just a heads up... this should be either >=0, >-1, or (my preference) !== -1, as this will fail in its current form if the string begins with the substring. – Karl White Feb 1 '14 at 8:07

The easyest way is indeed using indexOf. To just check a string string for a substring substr you can use this method:

string = "asdf";
substr = "as";
alert(string.indexOf(substr) == -1 ? false : true);

As you wanted the function string.contains(), you can implement it yourself like this:

String.prototype.contains = function(test) {
    return this.indexOf(test) == -1 ? false : true;
};

Now you can use this ecen shorter method to check if a string contains a special substring:

string = "asdf";
alert(string.contains("as"));

Here is a JSFiddle as well.

share|improve this answer

If you don't like the !!~, etc. tricks, you can simply add +1 to the result of .indexOf(). This way if a string is not found, -1 + 1 = 0 will be falsy, 0.. + 1 = 1.. will be truthy:

if ("StackOverflow".indexOf("Stack") + 1 )
    alert('contains');
else 
    alert('does not contain');
share|improve this answer
3  
Unreadable for human being... – jmcollin92 Oct 5 '14 at 16:34
1  
I perfectly agree, and I don't use it myself, but readability wasn't in the question :) – biziclop Oct 6 '14 at 9:11

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 ? "Found " + foundLinks + " title class" : "No title class found";
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 regular expression is a little overkill.

share|improve this answer

JavaScript code to use the contains 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 contains 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
2  
-1; this question is about strings, not arrays. – Mark Amery Apr 20 '14 at 16:49
3  
a string is an array of chars :) – daslicht Apr 22 '14 at 8:51
1  
The sample HTML is not well formed - the body tag is missing. – Peter Mortensen Oct 26 '14 at 10:22
result = 'GBP|1800';
//if pipe delimeter is there it returns true else false.
if(result.indexOf("|"))
{
    console.log('go default:' +result);
    var cur = result.substring(0, 3);//returns GBP
    console.log('go default cur:' +cur);
    var minmum_fee = result.substring(4);//gets the substring amount
    console.log('go default minmum_fee:' +minmum_fee);

}
else
{
    console.log('not found:' +result);
}
share|improve this answer

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

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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