Akercode.com

JavaScript String Contains

To find out if a string contains a certain substring in JavaScript we can use the includes() method, which was added to the ECMAScript 2015 (ES6) specification.

indexOf() is widely used and an effective way of checking if a string contains a substring.

Another technique can also be to use regular expression RegExp together with the test() method.

For older browsers that may not support this method you can easily polyfill the includes method.

includes()

The includes() method takes two parameters:

  • searchString, the substring to be searched for
  • position, optional (default is 0)

Substring bar is found in Foo bar:

'Foo bar'.includes('bar'); // true

foo does not exist in the string since it's case sensitive.

'Foo bar'.includes('foo'); // false

bar exists when starting from position 4:

'Foo bar'.includes('bar', 4); // true

Foo does not exist from position 1:

'Foo bar'.includes('Foo', 1); // false

indexOf()

The indexOf() method takes two parameters:

  • searchValue, the substring to be searched for
  • fromIndex, optional (default is 0)

The indexOf() method returns the index of the first occurrence of the found substring, or -1 if the substring is not found.

'Foo bar'.indexOf('soccer'); // -1

bar exists when starting fromIndex 4:

'Foo bar'.indexOf('bar', 4); // 4

A way of checking if a substring exists could be:

if ('Foo bar'.indexOf('Foo') !== -1) {
  // Substring exists, add logic here..
}

RegExp with test()

The RegExp object is used for matching text with a pattern, and with the test() method we can check a regular expression against a string.

const regex = new RegExp('fo*');

regex.test('Soccer is a type of football'); // true

In this case we are testing for a f character followed by a o character followed by a quantifier (*,matching 0 or more of the preceding token).

Polyfill the include method for old browsers

The official documentation at Mozilla has a way of polyfilling the include method.

Just remember to place it above any function calls.

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';

    if (search instanceof RegExp) {
      throw TypeError('first argument must not be a RegExp');
    }
    if (start === undefined) { start = 0; }
    return this.indexOf(search, start) !== -1;
  };
}