¿Cómo verificar si una cadena contiene una subcadena en JavaScript?

Por lo general, esperaría un String.contains() método, pero no parece haber uno.

¿Cuál es una forma razonable de comprobarlo?

preguntado el 24 de noviembre de 09 a las 10:11

3 Respuestas

ECMAScript 6 introducido String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring));

includes no es compatible con Internet Explorer, aunque. En ECMAScript 5 o entornos anteriores, utilice String.prototype.indexOf, que devuelve -1 cuando no se puede encontrar una subcadena:

var string = "foo";
var substring = "oo";

console.log(string.indexOf(substring) !== -1);

respondido 17 mar '20, 02:03

Hay un String.prototype.includes en ES6:

"potato".includes("to");
> true

Tenga en cuenta que este no funciona en Internet Explorer o en otros navegadores antiguos con soporte ES6 incompleto o nulo. Para que funcione en navegadores antiguos, es posible que desee utilizar un transpilador como Babel, una biblioteca de shim como es6-calce, o esto 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;
    }
  };
}

Respondido 22 ago 19, 14:08

solo curiosidad, ¿por qué necesitas comprobar la longitud? ¿IE falla en ese caso o algo así? - gman

También la comprobación de number no funciona como includes. Ejemplo: es6 incluye devoluciones falsas para "abc".includes("ab", "1") este polyfill devolverá verdadero - gman

Otra alternativa es KMP (Knuth – Morris – Pratt).

El algoritmo KMP busca una longitudm subcadena en una longitudn cadena en el peor de los casos O (n+m) tiempo, en comparación con el peor de los casos de O (nm) para el algoritmo ingenuo, por lo que el uso de KMP puede ser razonable si le preocupa la complejidad del tiempo en el peor de los casos.

Aquí hay una implementación de JavaScript del Proyecto Nayuki, tomada 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

contestado el 31 de mayo de 20 a las 18:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.