Home > Web Front-end > JS Tutorial > body text

JavaScript method to determine whether a string contains a specified substring_javascript skills

WBOY
Release: 2016-05-16 16:08:42
Original
1257 people have browsed it

The example in this article describes how JavaScript determines whether a string contains a specified substring. Share it with everyone for your reference. The specific analysis is as follows:

The following JS code defines a contains method for the String object to determine whether 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);
  };
}
Copy after login

The following is a detailed usage example, which can be executed in the browser

Copy code The code is as follows:
Enter two strings and check if Strign 1 contains String 2.
< br>
String 1:

String 2:



<script><br> if (!Array.prototype.indexOf) {<br> Array.prototype.indexOf = function(obj, start) {<br> for (var i = (start || 0), j = this.length; i < j; i ) {<br /> If (this[i] === obj) { return i; }<br />          }<br />           return -1;<br /> }<br /> }<br /> if (!String.prototype.contains) {<br /> String.prototype.contains = function (arg) {<br />           return !!~this.indexOf(arg);<br /> };<br /> }<br /> function checkstring() {<br /> var foo = document.getElementById("foo").value;<br /> var bar = document.getElementById("bar").value;<br /> alert(foo.contains(bar));<br /> }<br /> </script>

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template