fbpx

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

There are two simple ways to check if a string contains a substring in JavaScript. One of the ways is done using the includes method for JavaScript 6 (ECMAScript 6) and the other is with the indexOf for JavaScript 5 (ECMAScript 5) or older.

Option 1: Use the includes Method (ECMAScript 6)

The code snippet below shows you how to use the includes method to check if a string contains a substring in ECMAScript 6.

const str = 'We the People of the United States, in Order to form a more perfect Union.';

console.log(str.includes('We the'));       // true
console.log(str.includes('Order'));        // true
console.log(str.includes('notpresent'));   // false
console.log(str.includes('WE THE'));       // false
console.log(str.includes(''))              // true

if(str.includes('People')){
   // run this code if People is present in the str constant
}

Option 2: Use the indexOf Method (ECMAScript 5 or older)

The code example below shows how you can use the indexOf method to check if a string contains a substring in ECMAScript 5 or older.

var str = 'Green Monkey';
str.indexOf('Green');     // returns  0
str.indexOf('Groot');     // returns -1

if(str.indexOf('Green') !== -1){
   // run this code if Green is present in the str variable
}

Leave a Reply

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