Categories
JavaScript Answers

How to Check Whether a String Contains a Substring in JavaScript?

Spread the love

Checking whether a string has another substring is a common operation we do in JavaScript programs.

In this article, we’ll look at how to check whether a string has another substring in JavaScript.

String.prototype.includes

We can use the includes method that comes with string instances to check whether a string has a substring in JavaScript.

For instance, we can write:

const string = "foo";
const substring = "o";
console.log(string.includes(substring));

It returns true is the substring is in the string and false otherwise.

So this should return true .

We can also pass in a second argument with the index to start searching from.

So we can write:

console.log(str.includes('to be', 1))

to start searching str from index 1.

It’s included with ES6.

If we’re running a JavaScript program in an environment that doesn’t include ES6, we can add the following polyfill:

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

String.prototype.indexOf

Also, we can use the indexOf to get the first index of the substring in a string.

For instance, we can write:

const string = "foo";
const substring = "o";
console.log(string.indexOf(substring) !== -1);

If indexOf returns -1, then the substring isn’t in the string .

Otherwise, substring is in string .

Conclusion

We can use the indexOf or includes method to check whether a JavaScript substring is in another string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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