insensitive - javascript string substring




How to check whether a string contains a substring in JavaScript? (20)

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?


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

There is a string.includes in 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')

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

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.



Example

var a  = "Test String";

if(a.search("ring")!=-1){
     //exist 
} else {
     //not found 
}

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


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

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.


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.


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");
// [].reduce.call  : gives access to the reduce method on a HTMLCollection
// () => {}        : ES6 arrow function
const foundLinks = [].reduce.call(allLinks, (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.


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.


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 .


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

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

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 = stringVariable.search(findString) != -1;
document.write(containResult3+', ');
     
//using `split()`
var containResult4 = stringVariable.split(findString)[0] != stringVariable;
document.write(containResult4+'');


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

You can use jQuery's :contains selector.

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

Check it here: contains-selector


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

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




string-matching