How to check if a string contains a substring in JavaScript

JavaScript has rich library of functions to work with array and string. Sometimes working in Javascript, you might need to verify if a string contains specific substring or not.

This is same method as we use %Like% query with SQL. There are two ways, you can check if string contains substring.


String.prototype.includes() returns true if string contains any substring or not. For example,

var mainString = "";
var subString = "stuff";

console.log(mainString.includes(subString)); // true

String.prototype.includes was introduced in ECMAScript 6, which not support to Internet Explorer or older browsers.


String.prototype.indexOf supports ECMAScript 5 or older, so it will return -1 if string not contains substring. For example,

var mainString = "";
var subString = "stuff";

console.log(mainString.indexOf(subString) !== -1); // true

I hope you liked this article and it will help a little on your project.