How to Check If a String Contains a Sub String in JavaScript

In this short tip post, we will learn how to check if a string contains a substring using JavaScript.

Objective

We need to check whether the given word is present in the string as a substring.

Approach

We can use JavaScript indexOf() method to achieve the same. We can also use ES6 includes() method.

Code

var phrase = 'Hello, this is Shahid coding a JavaScript program';
var check = phrase.indexOf('Shahid') !== -1 ? true : false;
console.log(check); // true

You can also use ES6 includes() method is it is supported by your browser.

var phrase = 'Hello, this is Shahid coding a JavaScript program';
var check = phrase.includes('Shahid');
console.log(check); // true

Check out the codepen to view the live demo.

See the Pen
check substring javascript
by Shahid Shaikh (@codeforgeek)
on CodePen.

Love JavaScript? Learn more about it here.

Pankaj Kumar
Pankaj Kumar
Articles: 209