JavaScript determines whether a string contains a specified substring _javascript tips

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.