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

Pankaj Kumar is the founder and CEO of CodeForGeek, with more than 14 years in IT. He is an open-source enthusiast who enjoys sharing what he learns through CodeForGeek and YouTube, with a focus on Python, data analytics, machine learning, Angular, Node.js, and Kafka.

Articles: 335