Normalmente eu esperaria um método String.contains()
, mas parece que não't existe.
Qual é uma forma razoável de verificar isto?
ECMAScript 6 introduziu String.prototype.includes
:
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
Inclui' não tem suporte a Internet Explorer, no entanto. Em um ambiente ECMAScript 5 ou mais antigo, String.prototype.indexOf
, que retorna -1 quando não encontra o substring, pode ser utilizado em seu lugar:
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
Existe um 'String.prototype.includes' no ES6]1:
"potato".includes("to");
> true
Note que isto não funciona no Internet Explorer ou em outros navegadores antigos sem suporte ou com suporte incompleto do ES6. Para fazê-lo funcionar em navegadores antigos, você pode querer usar um transpiler como Babel, uma biblioteca de calços como es6-shim, ou este polyfill da MDN:
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
Outra alternativa é KMP (Knuth-Morris-Pratt).
O algoritmo KMP procura um substrato de comprimento-m numa cadeia de comprimento-n na pior das hipóteses O(n+m) tempo, em comparação com o pior caso de O(n⋅m) para o algoritmo ingénuo, por isso o uso do KMP pode ser razoável se você se preocupar com a complexidade do pior caso de tempo.
Aqui está um JavaScript implementado pelo Projeto Nayuki, retirado de https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:
// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.
function kmpSearch(pattern, text) {
if (pattern.length == 0)
return 0; // Immediate match
// Compute longest suffix-prefix table
var lsp = [0]; // Base case
for (var i = 1; i < pattern.length; i++) {
var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP
while (j > 0 && pattern.charAt(i) != pattern.charAt(j))
j = lsp[j - 1];
if (pattern.charAt(i) == pattern.charAt(j))
j++;
lsp.push(j);
}
// Walk through text string
var j = 0; // Number of chars matched in pattern
for (var i = 0; i < text.length; i++) {
while (j > 0 && text.charAt(i) != pattern.charAt(j))
j = lsp[j - 1]; // Fall back in the pattern
if (text.charAt(i) == pattern.charAt(j)) {
j++; // Next char matched, increment position
if (j == pattern.length)
return i - (j - 1);
}
}
return -1; // Not found
}
console.log(kmpSearch('ays', 'haystack') != -1) // true
console.log(kmpSearch('asdf', 'haystack') != -1) // false