I am looking for better options in Javascript to check if a string contains a substring. Substring can either be a text from an input field or database.
Sample:
var substring = "DVI to VGA" //some code to get text from input field or database
var string = "12 DVI To VGA adapter"
if(string.toLowerCase().indexOf(substring.toLowerCase()) != -1){
//any action after match
console.log("FOUND A MATCH")
}
I can't think of any, but you can encapsulate what you have in a function that is more concise and reusable:
function stringContainsSubstring(string, substring) {
return string.toLowerCase().indexOf(substring.toLowerCase()) != -1;
}
var contains = (string.toLowerCase()).includes(substring.toLowerCase());
not exactly a solution, but you can use it like:
if(~string.toLowerCase().indexOf(substring.toLowerCase()){...
looks a bit cleaner
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.