JavaScript Check if String Contains a Substring

  274 views   6 months ago 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()

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

var mainString = "laravelcode.com";
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

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

var mainString = "laravelcode.com";
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.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]