JavaScript determines whether a string contains the specified substring

  • 2020-05-16 06:23:11
  • OfStack

This article demonstrates how JavaScript determines whether a string contains a specified substring. Share with you for your reference. The specific analysis is as follows:

The JS code below defines an contains method for the String object to determine if the string contains substrings, 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);
  };
}

The following is a detailed usage example that can be executed in a browser

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 has been helpful to your javascript programming.


Related articles: