Does String Contains Substring
This javascript function returns true if the substring is contained within the string. If not it returns false. Javascript also provides the includes function supported by most browsers. For example, "Hello world".includes("world") returns true for most browsers, but is not supported in IE 6 through 11 and Opera Mini, and older versions of other browsers. See https://caniuse.com/?search=includes.
The following function works in all browsers:
// case insensitive
function contains(haystack, needle) {
if (haystack=="" || needle=="") { return false; }
haystack = haystack.toLowerCase();
needle = needle.toLowerCase();
return ​haystack.indexOf(needle) !== -1;
}
Example:
string = "Hello world.";
substring = "world";
if (contains(string, substring )) {
console.log("TRUE");
} else {
console.log("FALSE");
}
The console displays: TRUE
// this function is case sensitive
function contains(haystack, needle) {
if (haystack=="" || needle=="") { return false; }
return ​haystack.indexOf(needle) !== -1;
}