How to check whether a string contains a substring in JavaScript?

September 28, 2022 No comments javascript js string contains substring

Introduction

Sometimes, we want to check if a string contains a substring in JavaScript.

In this post, we'll present how to check if a string contains a substring in JS.

How to check whether a string contains a substring in JavaScript

To check if a string contains a substring in JavaScript we use string.indexOf(...) method:

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

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

If string.indexOf(substring) is equal to -1 it means that string doesn't contain given substring.

So to check if string contains another string we need to negate this condition: string.indexOf(substring) !== -1.

Conclusion

To check if string contains a substring we use string.indexOf(substring) method.

In ES6 we can use string.includes(substring) method to check if string contains another string.

{{ message }}

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