Site menu

CodeCook.io

  • Languages
    • C
    • C++
    • CSS
    • Git
    • HTML
    • Java
    • JavaScript
    • jQuery
    • PHP
    • Python
    • Ruby
    • Scala
  • contains
  • string
  • test

JavaScript - Test if string contains another string

String to search for within the sourceString
The position at which to begin search for searchString
0
452
  • Share on Facebook
  • Share on Google+
  • Share on Twitter

Native .contains()

The contains() method determines whether one string may be found within another string, returning true or false as appropriate. contains() on MDN.

Note: Only available since ECMAScript 6, which is currently in draft.

Usage without position
"{{sourceString}}".contains("{{searchString}}");
javascript
Usage with position
"{{sourceString}}".contains("{{searchString}}", {{position}});
javascript

Notes

  • Available since JavaScript 1.8.6 (ECMAScript 6)
true or false [boolean]

last update: Nov. 16, 2014

0
452
  • Share on Facebook
  • Share on Google+
  • Share on Twitter

Polyfill .contains()

Polyfill on MDN which adds .contains() method to String prototype when it doesn't exist (eg. older browsers).

Polyfill
if (!String.prototype.contains) {
    String.prototype.contains = function() {
        return String.prototype.indexOf.apply(this, arguments) !== -1;
  };
}
javascript
Usage without position
"{{sourceString}}".contains("{{searchString}}");
javascript
Usage with position
"{{sourceString}}".contains("{{searchString}}", {{position}});
javascript

Notes

  • Polyfill needs to be defined before calling method.
true or false [boolean]

last update: Nov. 16, 2014

0
452
  • Share on Facebook
  • Share on Google+
  • Share on Twitter

Helper contains()

As String.prototype.contains() is not yet standardised, you can use a helper function which uses indexOf() with the same arguments. The position argument is optional and is mapped to fromIndex in indexOf.

Helper
function contains(sourceString, searchString, position) {
   return String.prototype.indexOf.apply(sourceString, [searchString, position]) !== -1;
}
javascript
Usage without position
contains({{sourceString}}, {{searchString}});
javascript
Usage with position
contains({{sourceString}}, {{searchString}}, {{position}});
javascript

Notes

  • Does not modify native String.prototype.
true or false [boolean]

last update: Nov. 16, 2014

Advertisement

This project is hosted on DigitalOcean, try it and support us

Related concept

  • Repeat string
  • String length
  • String to uppercase
  • String to lowercase

Random task

  • Inline conditional
  • Get random item from array
  • Single comment
  • Select dom element by id
  • Font-face
  • Blog
  • About
  • License