Comment vérifier si une chaîne contient une chaîne en JavaScript

Mots clés : javascriptstringsubstringstring-matchingjavascript

meilleur 4 Réponses Comment vérifier si une chaîne contient une chaîne en JavaScript

vote vote

93

const string = "foo"; const substring = "oo";  console.log(string.includes(substring)); // true
var string = "foo"; var substring = "oo";  console.log(string.indexOf(substring) !== -1); // true
vote vote

84

"potato".includes("to"); > true 
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;     }   }; } 
vote vote

73

// 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
vote vote

64

git add --all git reset --hard HEAD 

Questions similaires