JavaScript String .contains()

JavaScript 2 2 Comments

String.prototype.contains() is a simple way of checking to see if a string contains another string. It’s one of the String extras in the upcoming ECMAScript 6 specification. Lucky for us, it’s easily polyfilled, and unlikely to change, so you can start using it right now. Here’s the basic usage:

Optionally, you can specify an index position to start searching from:

And here’s the basic polyfill:

As Mario mentioned in the comments, this function is generic, and works for Array contains, too:

So you can do:

Enjoy!


  1. Great. The polyfill can even be useful for a simple Array.contains()

    Array.prototype.contains = function(str){
      return ”.indexOf.call(this, str) !== -1;
    }
    var arr = ["ECMAScript","JavaScript"];
    arr.contains(“Script”); // true
    arr.contains(“script”); // false

    • Eric Elliott - October 17, 2013

      Yep… The generic feature is by design, and part of the ECMAScript spec. This works out of the box:




Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">