Este artigo descreve o método de JavaScript para determinar se uma string contém uma substring especificada. Compartilhe para sua referência. A análise específica é a seguinte:
O código JS a seguir define um método contém o método para o objeto String para determinar se uma string contém uma substring, o que é muito útil.
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; }} retornar -1; }} if (! string.prototype.contains) {string.prototype.contains = function (arg) {return !! ~ this.indexof (arg); };}Abaixo está um exemplo de uso detalhado que pode ser executado no navegador
Copie o código da seguinte forma: Digite duas seqüências e verifique se a STRING 1 contém string 2. <br> <br>
String 1: <input id = "foo" type = "text" value = "uma raposa marrom rápida salta"> <br>
String 2: <input id = "bar" type = "text" value = "fox jumps"> <br> <br>
<botão onclick = "checkString ()"> clique para verificar se a string 1 contém string 2 </button>
<Cript>
if (! Array.prototype.Indexof) {
Array.prototype.indexOF = function (obj, start) {
for (var i = (start || 0), j = this.length; i <j; i ++) {
if (este [i] === obj) {return i; }
}
retornar -1;
}
}
if (! string.prototype.contains) {
String.prototype.contains = function (arg) {
retornar !! ~ this.IndexOf (arg);
};
}
função checkString () {
var foo = document.getElementById ("foo").
var bar = document.getElementById ("bar").
alerta (foo.contains (bar));
}
</script>
Espero que este artigo seja útil para a programação JavaScript de todos.