JavaScript Check if String Contains a Substring
source link: https://www.laravelcode.com/post/javascript-check-if-string-contains-a-substring
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
JavaScript Check if String Contains a Substring
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
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]
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK