How to Check if a String Contains a Substring in Javascript

Updated

All modern programming languages provide multiple functions for manipulating and checking cases against strings. In JavaScript these native functions are called prototypes.

If you want to see if a string has another string within it using the JavaScript language you can use the simple following one-liner. The string within a string is called a substring.

How to check if a String contains a Substring Javascript

There are two ways of achieving this. The first method will work for all modern browsers.

ES6 Method for Modern Browsers

var string = "hello";
var substring = lo";

if (string.includes(substring)) {
  console.log('string contains substring');
}

ES5 Method for Internet Explorer and Older Browsers

var string = "hello";
var substring = lo";

if (string.indexOf(substring) !== -1) {
  console.log('string contains substring');
}

That’s all there is to checking is strings have substrings using native Javascript prototypes.