JavaScript - Test if string contains another string
The contains() method determines whether one string may be found within another string, returning true or false as appropriate. contains() on MDN.
Note: Only available since ECMAScript 6, which is currently in draft.
Usage without position
"{{sourceString}}".contains("{{searchString}}");
Usage with position
"{{sourceString}}".contains("{{searchString}}", {{position}});
Polyfill on MDN which adds .contains()
method to String prototype when it doesn't exist (eg. older browsers).
Polyfill
if (!String.prototype.contains) {
String.prototype.contains = function() {
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
}
Usage without position
"{{sourceString}}".contains("{{searchString}}");
Usage with position
"{{sourceString}}".contains("{{searchString}}", {{position}});
As String.prototype.contains()
is not yet standardised, you can use a helper function which uses indexOf()
with the same arguments. The position
argument is optional and is mapped to fromIndex
in indexOf
.
Helper
function contains(sourceString, searchString, position) {
return String.prototype.indexOf.apply(sourceString, [searchString, position]) !== -1;
}
Usage without position
contains({{sourceString}}, {{searchString}});
Usage with position
contains({{sourceString}}, {{searchString}}, {{position}});