DEV Community

John Au-Yeung
John Au-Yeung

Posted on • Originally published at thewebdev.info

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

Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62

Subscribe to my email list now at http://jauyeung.net/subscribe/

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));
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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;
  };
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More