This article describes the method of JavaScript to determine whether a string contains a specified substring. Share it for your reference. The specific analysis is as follows:
The following JS code defines a contains method for the String object to determine whether a string contains a substring, which is very useful.
if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(obj, start) { for (var i = (start || 0), j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; }}if (!String.prototype.contains) { String.prototype.contains = function (arg) { return !!~this.indexOf(arg); };}Below is a detailed usage example that can be executed in the browser
Copy the code as follows: Enter two strings and check if Strign 1 contains String 2.<br> <br>
String 1: <input id="foo" type="text" value="a quick brown fox jumps over"> <br>
String 2: <input id="bar" type="text" value="fox jumps"> <br><br>
<button onclick="checkstring()">Click to check if String 1 contains String 2</button>
<script>
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}
if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}
function checkstring() {
var foo = document.getElementById("foo").value;
var bar = document.getElementById("bar").value;
alert(foo.contains(bar));
}
</script>
I hope this article will be helpful to everyone's JavaScript programming.