The example in this article describes how JavaScript determines whether a string contains a specified substring. Share to everyone for your reference. The specific analysis is as follows:
The following JS code, which is useful for a string object, defines a contains method for determining whether a string contains substrings.
if (! Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, start) {
for (var i = (Start | | 0), j = This.le Ngth; I < J; i++) {
if (this[i] = = obj) {return i;}
}
Return-1
}
}
if (! String.prototype.contains) {
String.prototype.contains = function (ARG) {return
!! ~this.indexof (ARG);}
;
}
The following is a detailed example of usage that can be performed in a browser
Copy Code 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 help you with your JavaScript programming.