Di solito mi aspetterei un metodo String.contains()
, ma non sembra essercene uno.
Qual è un modo ragionevole per controllare questo?
ECMAScript 6 ha introdotto String.prototype.includes
:
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
include
non ha il supporto di Internet Explorer, però. In un ambiente ECMAScript 5 o più vecchio, si può usare invece String.prototype.indexOf
, che restituisce -1 quando non trova la sottostringa:
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
C'è un String.prototype.includes
in ES6:
"potato".includes("to");
> true
Si noti che questo non funziona in Internet Explorer o in alcuni altri vecchi browser con supporto ES6 assente o incompleto. Per farlo funzionare nei vecchi browser, potresti voler usare un transpiler come Babel, una libreria shim come es6-shim, o questo 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;
}
};
}
Un'altra alternativa è KMP (Knuth-Morris-Pratt).
L'algoritmo KMP cerca una sottostringa di lunghezza-m in una stringa di lunghezza-n nel caso peggiore in tempo O(n+m), rispetto ad un caso peggiore di O(n⋅m) per l'algoritmo ingenuo, quindi usare KMP può essere ragionevole se vi interessa la complessità del caso peggiore.
Ecco un'implementazione JavaScript di Project Nayuki, presa da 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