Cómo comprobar si una cadena contiene una subcadena en JavaScript?


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

¿Cuál es una manera razonable de verificar esto?

Author: Peter O., 2009-11-24

30 answers

Aquí hay una lista de posibilidades actuales:

1. (ES6) includes-ir a la respuesta

var string = "foo",
    substring = "oo";
string.includes(substring);

2. ES5 y mayores indexOf

var string = "foo",
    substring = "oo";
string.indexOf(substring) !== -1;

String.prototype.indexOf devuelve la posición de la cadena en otra cadena. Si no se encuentra, devolverá -1.

3. search-ir a la respuesta

var string = "foo",
    expr = /oo/;
string.search(expr);

4. lodash incluye-ir a la respuesta

var string = "foo",
    substring = "oo";
_.includes(string, substring);

5. RegExp-ir a respuesta

var string = "foo",
    expr = /oo/;  // no quotes here
expr.test(string);

6. Partido-ir a la respuesta

var string = "foo",
    expr = /oo/;
string.match(expr);

Las pruebas de rendimiento muestran que indexOf podría ser la mejor opción, si se llega a un punto en el que la velocidad importa.

 11731
Author: Fabien Ménager,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-28 12:31:10

Puede agregar fácilmente un método contains a String con esta instrucción:

String.prototype.contains = function(it) { return this.indexOf(it) != -1; };

Nota: vea los comentarios a continuación para un argumento válido para no usar esto. Mi consejo: usa tu propio juicio.

Alternativamente:

if (typeof String.prototype.contains === 'undefined') { String.prototype.contains = function(it) { return this.indexOf(it) != -1; }; }
 840
Author: Avi Flax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-28 01:32:52

El problema con su código es que JavaScript distingue entre mayúsculas y minúsculas. Su método de llamada

indexof()

Debería ser

indexOf()

Intente arreglarlo y vea si eso ayuda:

if (test.indexOf("title") !=-1) {
    alert(elm);
    foundLinks++;
}
 441
Author: Victor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-18 19:24:03

Hay un string.includes en ES6:

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

Tenga en cuenta que puede necesitar cargar es6-shim o similar para que esto funcione en navegadores más antiguos.

require('es6-shim')
 383
Author: eliocs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-13 15:57:05
var index = haystack.indexOf(needle);
 347
Author: pixeline,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-24 13:06:27

Podría usar el método JavaScript search().

La sintaxis es: string.search(regexp)

Devuelve la posición de la coincidencia, o -1 si no se encuentra ninguna coincidencia.

Ver ejemplos allí: jsref_search

No necesita una sintaxis de expresión regular complicada. Si usted no está familiarizado con ellos un simple st.search("title") hará. Si desea que su prueba sea insensible a mayúsculas y minúsculas, entonces debe hacer st.search(/title/i).

 241
Author: Tardis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-22 18:25:39

String.prototype.includes() se introdujo en ES6.

Determina si una cadena puede encontrarse dentro de otra cadena, devolver verdadero o falso según corresponda.

Sintaxis

var contained = str.includes(searchString [, position]);  

Parámetros

searchString

Una cadena a buscar dentro de esta cadena.

position

La posición en esta cadena en la que comenzar a buscar searchString por defecto es 0.

Ejemplo

var str = "To be, or not to be, that is the question.";

console.log(str.includes("To be"));    // true
console.log(str.includes("question")); // true
console.log(str.includes("To be", 1)); // false  

Nota

Esto puede requerir ES6 shim en navegadores antiguos.

 171
Author: Aniket Kulkarni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-25 06:40:47

Si estabas buscando una alternativa para escribir la comprobación -1 fea, antepones una ~ tilde en su lugar.

if (~haystack.indexOf('needle')) alert('found');

Joe Zimmerman - verás que usar ~ on -1 lo convierte en 0. El número 0 es un falsey valor, lo que significa que se evaluará a falso cuando se convierte a un booleano. Eso podría no parecer una gran idea al principio, pero recuerde que las funciones como indexOf devolverán -1 cuando la consulta no sea encontrar. Esto significa que en lugar de escribir algo similar a esto:

if (someStr.indexOf("a") >= 0) {
  // Found it
} else  {
  // Not Found
}

Ahora puede tener menos caracteres en su código para que pueda escribirlo así:

if (~someStr.indexOf("a")) {
  // Found it
} else  {
  // Not Found
}

Más detalles aquí

 124
Author: ᴉʞuǝ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-21 06:12:11

Este fragmento de código debería funcionar bien:

var str="This is testing for javascript search !!!";
if(str.search("for") != -1) {
   //logic
} 
 86
Author: vaibhav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-30 07:31:32

Una forma común de escribir un método contains en JavaScript es:

if (!String.prototype.contains) {
    String.prototype.contains = function (arg) {
        return !!~this.indexOf(arg);
    };
}

El operador de negación bit a bit (~) se usa para convertir -1 en 0 (falsey), y todos los demás valores serán distintos de cero (truth).

Los operadores de negación booleana doble se utilizan para convertir el número en un booleano.

 81
Author: zzzzBov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-26 13:38:59

In ES5

var s = "foo";
alert(s.indexOf("oo") > -1);
{[5] {} En[6]}ES6 hay tres nuevos métodos: includes(), startsWith(), endsWith().

var msg = "Hello world!";

console.log(msg.startsWith("Hello"));       // true
console.log(msg.endsWith("!"));             // true
console.log(msg.includes("o"));             // true

console.log(msg.startsWith("o", 4));        // true
console.log(msg.endsWith("o", 8));          // true
console.log(msg.includes("o", 8));          // false
 80
Author: Nisar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-16 23:27:36

En lugar de usar fragmentos de código que se encuentran aquí y allá en la web, también puede usar una biblioteca bien probada y documentada. Dos Opciones que recomendaría:


1a opción: Use Lodash : Tiene un includes método:

_.includes('foobar', 'ob');
// → true

Lodash es la dependencia de bibliotecas javascript más popular para npm y tiene un montón de útiles métodos de utilidad javascript. Así que para muchos proyectos querrías esto de todos modos; -)


2a opción: O use Subrayado.cadena: tiene un include método:

_.str.include('foobar', 'ob');
// → true

Aquí está la descripción de Subrayado.string, solo agrega 9kb pero le da todas las ventajas que una biblioteca bien probada y documentada tiene sobre los fragmentos de código de copy'n'peak:

Subrayado.string es una biblioteca JavaScript para una manipulación cómoda con cadenas, extensión para subrayado.js inspirado en Prototype.js, Derecho.js, Underscore y hermoso lenguaje Ruby.

Subrayado.string le proporciona varias funciones útiles: capitalizar, clean, includes, count, escapeHtml, unescapeHTML, insert, splice, startsWith, endsWith, titleize, trim, truncate y así sucesivamente.

Nota bien, subrayado.la cadena está influenciada por el subrayado.js pero se puede usar sin él.


Por último, no menos importante: Con la versión JavaScript ES6 viene un includes método:

'foobar'.includes('ob');
// → true

La mayoría de los navegadores modernos ya lo soportan, tenga un ojo en la tabla de compatibilidad ES6 .

 69
Author: nachtigall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-03 22:09:28

Puede usar el selector :contains de jQuery.

$("div:contains('John')")

Comprobar aquí: contiene selector

 67
Author: Chorinator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-04 04:38:49

Use una expresión regular:

RegExp.test(string)

 63
Author: rahul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-21 18:38:48

Otra opción para hacer esto es:

Puede usar la función match, es decir, algo así como:

x = "teststring";

if (x.match("test")) {
     // Code
}

Match() también puede trabajar con expresiones regulares:

x = "teststring";

if (x.match(/test/i)) {
     // Code
}
 56
Author: David Craig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-26 08:50:20

Estabas buscando .indexOfMDN.

indexOf va a devolver un índice a la subcadena coincidente. El índice se correlacionará con el lugar donde comienza la subcadena. Si no hay coincidencia, se devuelve un -1. Aquí está un demostración simple de ese concepto:

var str = "Hello World"; // For example, lets search this string,
var term = "World"; // for the term "World",
var index = str.indexOf(term); // and get its index.
if (index != -1) { // If the index is not -1 then the term was matched in the string,
  alert(index); // and we can do some work based on that logic. (6 is alerted)
}
 52
Author: Travis J,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-27 11:43:43

Debe llamar a indexOf con una "O" mayúscula como se mencionó. También debe tenerse en cuenta, que en clase JavaScript es una palabra reservada, es necesario utilizar className para obtener este atributo de datos. La razón por la que probablemente está fallando es porque está devolviendo un valor nulo. Puede hacer lo siguiente para obtener el valor de su clase...

var test = elm.getAttribute("className");
//or
var test = elm.className
 51
Author: MillsJROSS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-24 15:52:20

Esto simplemente funcionó para mí. Selecciona cadenas que no contienen el término "Deleted:"

if (eventString.indexOf("Deleted:") == -1)
 51
Author: writtinfool,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-20 01:35:31

Dado que la pregunta es bastante popular, pensé que podría agregar un poco de sabor moderno al código.

// const           : creates an immutable constant
const allLinks   = document.getElementsByTagName("a");
// [].reduce.call  : gives access to the reduce method on a HTMLCollection
// () => {}        : ES6 arrow function
const foundLinks = [].reduce.call(allLinks, (sum, link) => {
     // bitwise OR : converts the boolean value to a number
     return sum + (link.classList.contains("title") | 0);
}, 0);

// template literal
console.log(`Found ${foundLinks || "no"} title class`);

Por cierto, la respuesta correcta es escribir mal indexOf o el no estándar String.contains. Cargar una biblioteca externa (especialmente si el código está escrito en JavaScript puro) o jugar con String.prototype o usar una expresión regular es un poco exagerado.

 36
Author: Jay Harris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-19 14:32:05

Hay una manera elegante y mejor de hacer esto y está utilizando el operador (BitWise NOT).

if(~"John".indexOf("J")) {
  alert("Found")
}
else {
  alert("Not Found");
}

El Bitwise No convierte "x" en -(x + 1) por lo tanto, si la x resulta -1 del método indexOf.luego se convertirá en - (-1 + 1) = -0, que es un valor falso .

 28
Author: Kiba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-07 11:05:58

String.prototype.indexOf() o String.prototype.search()?!

Como otros ya han mencionado, las cadenas de JavaScript tienen indexOf y search método.

La diferencia clave entre ambos es que indexOf es solo para subcadenas simples, mientras que search también admite expresiones regulares. Por supuesto, una ventaja de usar indexOf es que es más rápido.

Véase también En JavaScript, ¿cuál es la diferencia entre indexOf () y search ()?.

Implementando su método propio String.prototype.contains()

Si desea agregar su propio método contains a cada cadena, la mejor manera de hacerlo sería @zzzzBov's enfoque:

if (!String.prototype.contains) {
    String.prototype.contains = function (arg) {
        return !!~this.indexOf(arg);
    };
}

Lo usarías así: {[25]]}

'Hello World'.contains('orl');

Implementando una biblioteca de utilidades personalizada

Generalmente está mal visto agregar sus propios métodos personalizados a objetos estándar en JavaScript, por ejemplo, porque podría romper la compatibilidad hacia adelante.

Si realmente quieres tu propio contains método y / u otro métodos de cadena personalizados, es mejor crear su propia biblioteca de utilidades y agregar sus métodos de cadena personalizados a esa biblioteca:

var helper = {};

helper.string = {
    contains : function (haystack, needle) {
        return !!~haystack.indexOf(needle);
    },
    ...
};

Lo usarías así: {[25]]}

helper.string.contains('Hello World', 'orl');

Usando una biblioteca de utilidades de terceros

Si no desea crear su propia biblioteca de ayuda personalizada, siempre existe, por supuesto, la opción de usar una biblioteca de utilidad de terceros. Como mencionó @nachtigall , los más populares son Lodash y Subrayado.js .

En Lodash, puedes usar _.includes(), que usas así: {[25]]}

_.includes('Hello World', 'orl');

En subrayado.js, puedes usar _.str.include(), que usas así:

_.str.include('Hello World', 'orl');
 27
Author: John Slegers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37

Ejemplo

var a  = "Test String";

if(a.search("ring")!=-1){
     //exist 
} else {
     //not found 
}
 25
Author: Ali Abbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-31 06:06:34

Solución simple

if (!String.prototype.contains) {
  String.prototype.contains= function() {
    return String.prototype.indexOf.apply(this, arguments) !== -1;
  };
}

Se puede utilizar de la siguiente manera

"hello".contains("he") // true
"hello world".contains("lo w")//true
"hello world".contains("lo wa")//false
"hello world".contains(" ")//true
"hello world".contains("  ")//false

Referencia MDN

 24
Author: Sriramajeyam Sugumaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-21 09:45:55
 24
Author: 2 revsuser663031,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-02 19:19:38

Código JavaScript para usar el método contains en una matriz:

<html>
    <head>
        <h2>Use of contains() method</h2>
        <script>
            Array.prototype.contains = function (element) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] == element) {
                        return true;
                    }
                }
                return false;
            }
            arr1 = ["Rose", "India", "Technologies"];
            document.write("The condition is "+arr1.contains("India")+"<br>");
        </script>
    </head>

    <b>[If the specified element is present in the array, it returns true otherwise
    returns false.]</b>

</html>

En el código dado el método contains determina si el elemento especificado está presente en el array o no. Si el elemento especificado está presente en la matriz, devuelve true, de lo contrario devuelve false.

 21
Author: Tarun Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-26 10:21:27

Para recoger algún tipo de soluciones válidas:

var stringVariable = "some text";
var findString = "text";

//using `indexOf()`
var containResult1 = stringVariable.indexOf(findString) != -1;
document.write(containResult1+', ');

//using `lastIndexOf()`
var containResult2 = stringVariable.lastIndexOf(findString) != -1;
document.write(containResult2+', ');

//using `search()`
var containResult3 = stringVariable.search(findString) != -1;
document.write(containResult3+', ');
     
//using `split()`
var containResult4 = stringVariable.split(findString)[0] != stringVariable;
document.write(containResult4+'');
 20
Author: shA.t,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-18 04:43:38

Ya que hay una queja sobre el uso del prototipo, y ya que usar indexOf hace que su código sea menos legible, y ya que la expresión regular es excesiva:

function stringContains(inputString, stringToFind) {
    return (inputString.indexOf(stringToFind) != -1);
}

Ese es el compromiso por el que terminé yendo.

 18
Author: Tjaart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-25 12:22:31

JavaScript

 var str = "My big string contain apples and oranges";
 var n = str.indexOf("apples"); 
 alert(n); //will alert 22, -1 if not found

JQuery

  <p>My big string contain apples and oranges</p>
  alert($("p:contains(apples)")[0] != undefined); //will alert true if found
 17
Author: Alain Gauthier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-16 18:44:26

Utilice el incorporado y más simple es decir, match() en la cadena. Para lograr lo que espera hacer esto:

var stringData ="anyString Data";

var subStringToSearch = "any";

// This will give back the substring if matches and if not returns null
var doesContains = stringData.match(subStringToSearch);

if(doesContains !=null) {
    alert("Contains Substring");
}
 13
Author: Ankur Madaan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-02 20:26:01

La forma más fácil es usar indexOf. Para simplemente comprobar una cadena string para una subcadena substr puede utilizar este método:

string = "asdf";
substr = "as";
alert(string.indexOf(substr) == -1 ? false : true);

Como querías la función string.contains(), puedes implementarla tú mismo de la siguiente manera:

String.prototype.contains = function(test) {
    return this.indexOf(test) == -1 ? false : true;
};

Ahora puede usar este método ecen shorter para verificar si una cadena contiene una subcadena especial:

string = "asdf";
alert(string.contains("as"));

Aquí hay un JSFiddle también.

 13
Author: frieder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-26 10:30:27