How to check whether a string contains a substring in JavaScript?

gramm Source

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



answered 8 years ago Fabien Ménager #1

Here is a list of current possibilities:

1. indexOf

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

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

2. (ES6) includesgo to answer, or this answer

var string = "foo",
    substring = "oo";

3. searchgo to answer

var string = "foo",
    expr = /oo/;;

4. lodash includesgo to answer

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

5. RegExpgo to answer

var string = "foo",
    expr = /oo/;  // no quotes here

6. Matchgo to answer

var string = "foo",
    expr = /oo/;

Performance tests are showing that indexOf might be the best choice, if it comes to a point where speed matters.

answered 8 years ago pixeline #2

var index = haystack.indexOf(needle);

answered 8 years ago rahul #3

Use a regular expression:


answered 8 years ago Victor #4

The problem with your code is that JavaScript is case sensitive. Your method call


should actually be


Try fixing it and see if that helps:

if (test.indexOf("title") !=-1) {

answered 8 years ago MillsJROSS #5

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");
var test = elm.className

answered 8 years ago Avi Flax #6

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.


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

answered 8 years ago Tardis #7

You could use the JavaScript search() method.

Syntax is:

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"title") will do. If you want your test to be case insensitive, then you should do

answered 7 years ago Chorinator #8

You can use jQuery's :contains selector.


Check it here: contains-selector

answered 6 years ago writtinfool #9

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

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

answered 6 years ago vaibhav #10

This piece of code should work well:

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

answered 5 years ago zzzzBov #11

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.

answered 5 years ago David Craig #12

Another option of doing this is:

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

x = "teststring";

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

match() can also work with regular expression :

x = "teststring";

if (x.match(/test/i)) {
     // Code

answered 5 years ago eliocs #13

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

> true

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


answered 5 years ago Tarun Gupta #14

JavaScript code to use the contains method in an array:

        <h2>Use of contains() method</h2>
            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>");

    <b>[If the specified element is present in the array, it returns true otherwise
    returns false.]</b>


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.

answered 4 years ago Tjaart #15

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.

answered 4 years ago Travis J #16

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)

answered 4 years ago Aniket Kulkarni #17

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

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


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



A string to be searched for within this string.


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


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  


This may require ES6 shim in older browsers.

answered 4 years ago Jay Harris #18

Since the question is pretty popular, I thought I could add a little modern flavor to the code.

// const           : creates an immutable constant
const allLinks   = document.getElementsByTagName("a");
// []  : gives access to the reduce method on a HTMLCollection
// () => {}        : ES6 arrow function
const foundLinks = [], (sum, link) => {
     // bitwise OR : converts the boolean value to a number
     return sum + (link.classList.contains("title") | 0);
}, 0);

// template literal
console.log(`Found ${foundLinks || "no"} title class`);

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.

answered 4 years ago Oliver Ni #19

Try this:

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

Here is an example: jsfiddle

answered 4 years ago nachtigall #20

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:

// → true

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

answered 4 years ago Satish Sharma #21

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

answered 4 years ago biziclop #22

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('does not contain');

answered 4 years ago Ankur Madaan #23

Use the inbuilt and simplest one i.e match() on the string. To achieve what you are looking forward do this:

var stringData ="anyString Data";

var subStringToSearch = "any";

// This will give back the substring if matches and if not returns null
var doesContains = stringData.match(subStringToSearch);

if(doesContains !=null) {
    alert("Contains Substring");

answered 4 years ago Christian Landgren #24

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

answered 4 years ago frieder #25

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

Here is a JSFiddle as well.

answered 3 years ago Developer #26

result = 'GBP|1800';
//if pipe delimeter is there it returns true else false.
    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);

    console.log('not found:' +result);

answered 3 years ago Developer MJ #28

One more function, search:

var str = "Stack Overflow";
var n ="Overflow");
if (n != -1)
    alert('String exists')

answered 3 years ago Mark Benny #29

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

if(~"John".indexOf("J")) {
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 .

answered 3 years ago Alain Gauthier #30


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


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

answered 3 years ago shA.t #31

To collect some kind of valid solutions:

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

//using `indexOf()`
var containResult1 = stringVariable.indexOf(findString) != -1;
document.write(containResult1+', ');

//using `lastIndexOf()`
var containResult2 = stringVariable.lastIndexOf(findString) != -1;
document.write(containResult2+', ');

//using `search()`
var containResult3 = != -1;
document.write(containResult3+', ');
//using `split()`
var containResult4 = stringVariable.split(findString)[0] != stringVariable;

answered 3 years ago Nisar #32

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

answered 3 years ago Sriramajeyam Sugumaran #33

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

answered 2 years ago Sherali Turdiyev #34

I know that best way is str.indexOf(s) !== -1;

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

answered 2 years ago Ali Abbas #35


var a  = "Test String";

} else {
     //not found 

answered 2 years ago John Slegers #36

String.prototype.indexOf() or!

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');

answered 2 years ago user6139219 #37

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
  //substring does not exist

answered 2 years ago Josip Ivic #38

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

answered 2 years ago Devashish Jaiswal #39

There are multiple ways to do this. The most frequently used would be the indexOf() method. indexOf() returns the position of the string passed to it as argument and -1 if the string doesn't contain the passed string.

let str = "A cat and a dog";
str.indexOf("cat"); // returns 2
str.indexOf("panda"); // returns -1

answered 1 year ago Raman Sahasi #40

With ECMAScript 2015, we can use includes()

let s = "foo";

answered 1 year ago سیدرسول میرعظیمی #41

Using Indexof that can be identified easily, Example:

var array = [2, 9, 9];
array.indexOf(2);     // 0
array.indexOf(7);     // -1
array.indexOf(9, 2);  // 2
array.indexOf(2, -1); // -1
array.indexOf(2, -3); // 0

The result is in comment after the line

answered 1 year ago F. Hauri #42

Yet another answer...

Usually, I would expect a String.contains() method,...

Depending on what usually mean, there is at least one way not already presented on all previous answer.

This could be usefull on very specific cases, but:

var mystring="Foo bar baz"
var searchstr="bar"
var arraysplt=mystring.split(searchstr)
var containbool=typeof(arraysplt[1])=="string";

If searchstr is present at least once, even at end of mystring, then typeof(split(...)[1]) is string (an empty string). If not present, then typeof(split(...)[1]) become undefined.


typeof( mystring.split( searchstr )[1] ) == "string";

But using this method could only be usefull only if arraysplt's elements will be usefull lather in the script.

... so this shorted method seem completely useless (I think)...

But, if your goal is to split a string, using indexOf to ensure presence of separator is useless.

answered 12 months ago Kamil Ibadov #43

Simple answer, works 100%

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

some examples

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

answered 10 months ago Abi #44

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

answered 10 months ago Alireza #45

In ES6, we have something calls includes which does exactly what you want: So you can simply do this:


Also in ES5, if you widely use it, you can simply add it like this:

String.prototype.includes = String.prototype.includes || function(str) {
  return this.indexOf(str) > -1;

answered 8 months ago wz366 #46

I'm surprised no one has mentioned KMP here. What is KMP? KMP algorithm provides worst-case linear time substring search, so it is a reasonable way if you do care about worst-case time complexity. Link to JavaScript KMP implementation sample

answered 7 months ago Behnam Mohammadi #47

Very simple:

var a = "foo", b= "oo";
if (a.indexOf(substring) !== -1) {
    // has

answered 4 weeks ago Suchi #48

The indexOf method is the best solution as it is supported by all the browsers

The syntax is : string.indexOf(searchvalue, start)

where start is an optional parameter.

answered 4 weeks ago Andrei Todorut #49

You can easy check if a substring is in a string with indexOf method.

In javascript and other programming languages the strings are like arrays

For example:

var str = "Hello String";
// str[0] => H

Find the first occurrence of substring:

str.indexOf("l") // returns 2

And last occurrence of substring:

str.lastIndexOf("l") // returns 3

comments powered by Disqus