Cet article décrit la méthode de JavaScript pour déterminer si une chaîne contient une sous-chaîne spécifiée. Partagez-le pour votre référence. L'analyse spécifique est la suivante:
Le code JS suivant définit une méthode contient pour l'objet String pour déterminer si une chaîne contient une sous-chaîne, ce qui est très utile.
if (! array.prototype.indexof) {array.prototype.indexof = fonction (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); };}Vous trouverez ci-dessous un exemple d'utilisation détaillé qui peut être exécuté dans le navigateur
Copiez le code comme suit: Entrez deux chaînes et vérifiez si Strign 1 contient la chaîne 2. <br> <br>
String 1: <IND ID = "FOO" Type = "Text" Value = "Un renard brun rapide saute"> <br>
String 2: <input id = "bar" type = "text" value = "Fox saute"> <br> <br>
<bouton onClick = "Checkstring ()"> Cliquez pour vérifier si la chaîne 1 contient la chaîne 2 </ bouton>
<cript>
if (! array.prototype.indexof) {
Array.prototype.indexof = fonction (obj, start) {
pour (var i = (start || 0), j = this.length; i <j; i ++) {
if (this [i] === obj) {return i; }
}
retour -1;
}
}
if (! string.prototype.contains) {
String.prototype.contains = fonction (arg) {
return !! ~ this.indexof (arg);
};
}
fonction Checkstring () {
var foo = document.getElementById ("foo"). valeur;
var bar = document.getElementById ("bar"). valeur;
alerte (foo.Conains (bar));
}
</cript>
J'espère que cet article sera utile à la programmation JavaScript de tous.