Normalement, je m'attendrais à ce qu'il existe une méthode String.contains()
, mais il ne semble pas y en avoir.
Quel est le moyen raisonnable de vérifier ce point ?
ECMAScript 6 a introduit [String.prototype.includes
][3] :
var string = "foo",
substring = "oo";
console.log(string.includes(substring));
includes
[n'a pas de support pour Internet Explorer][2], cependant. Dans un environnement ECMAScript 5 ou plus ancien, [String.prototype.indexOf
][1], qui renvoie -1 lorsqu'il ne trouve pas la sous-chaîne, peut être utilisé à la place :
var string = "foo",
substring = "oo";
console.log(string.indexOf(substring) !== -1);
[1] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf [2] : https://caniuse.com/#feat=es6-string-includes [3] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
[Il existe un String.prototype.includes
dans ES6][1] :
"potato".includes("to");
> true
Notez que cela [ne fonctionne pas dans Internet Explorer ou certains autres anciens navigateurs] (https://caniuse.com/?v=1#feat=es6-string-includes) dont la prise en charge de ES6 est nulle ou incomplète. Pour le faire fonctionner dans les anciens navigateurs, vous pouvez utiliser un transpilateur comme Babel, une bibliothèque de shim comme es6-shim, ou ce polyfill de 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;
}
};
}
[1] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
Une autre alternative est KMP (Knuth-Morris-Pratt).
L'algorithme KMP recherche une sous-chaîne de longueurm dans une chaîne de longueurn en un temps O(n+m) dans le pire des cas, comparé à un temps O(n⋅m) dans le pire des cas pour l'algorithme naïf, donc l'utilisation de KMP peut être raisonnable si vous vous souciez de la complexité du temps dans le pire des cas.
Voici une mise en œuvre JavaScript par Project Nayuki, tirée 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
[2] : https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js