How to check if a string contains a substring in JavaScript

January 05, 2020 No comments JavaScript QA Snippets Examples Contains Substring

1. Introduction

In this short article, we are going to show a method to check whether one string contains another in JavaScript.

2. Using indexof() method

The one method comes from the original vanilla JS. We can simply use indexOf() function on String object that takes the substring value to search for.


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

console.log(string.indexOf(substring) !== -1); // true
console.log(string.indexOf("foof") !== -1); // false


3. Using includes() method from ES6

ES6 comes with the function includes() that determines whether one string may be found within another.


const string = "foo";
const substring = "oo";

console.log(string.includes(substring)); // true
console.log(string.includes("foof")); // false


4. Polyfill of includes() method

If you want to be 100% sure that includes() method will be available on all browsers you can add polyfill that could look like the following:

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

5. Conclusion

In this article, we showed a way to check if one string may be found within another string. We used indexOf method and includes() that was introduced in ECMAScript 6.

{{ message }}

{{ 'Comments are closed.' | trans }}