Búsqueda de cadenas de JavaScript


Tabla de contenido

    Mostrar tabla de contenidos

Métodos de búsqueda de cadenas

  • String indexOf()
  • String lastIndexOf()
  • String search()
  • String match()
  • String matchAll()
  • String includes()
  • String startsWith()
  • String endsWith()

Índice de cadena de JavaScript de()

El método indexOf() devuelve el index (posición) la primera aparición de una cadena en una cadena:

Ejemplo

let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>

<p>The indexOf() method returns the position of the first occurrence of a string in a string.</p>
<p>The position of the first occurrence of "locate" is:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>

Nota

JavaScript cuenta las posiciones desde cero.

0 es la primera posición en un cadena, 1 es el segundo, 2 es el tercero, ...


Cadena de JavaScript lastIndexOf()

El método lastIndexOf() devuelve el índice del último aparición de un texto específico en una cadena:

Ejemplo

let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The lastIndexOf() Method</h2>

<p>The position of the last occurrence of "locate" is:</p>

<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>

Tanto indexOf() como lastIndexOf() devuelven -1 si no se encuentra el texto:

Ejemplo

let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("John");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>

<p>Both indexOf() and lastIndexOf() return -1 if the text is not found:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("John");
document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>

Ambos métodos aceptan un segundo parámetro como posición inicial para el buscar:

Ejemplo

let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The indexOf() Method</h2>

<p>The indexOf() method accepts a second parameter as the starting position for the search:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate",15);
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>

Los métodos lastIndexOf() buscan hacia atrás (desde el final hasta el principio), es decir: si el segundo parámetro es 15, la búsqueda comienza en la posición 15 y busca hasta el principio de la cadena.

Ejemplo

let text = "Please locate where 'locate' occurs!";
text.lastIndexOf("locate", 15);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The lastIndexOf() Method</h2>

<p>The lastIndexOf() method accepts a second parameter as the starting position for the search.</p>
<p>Remember that the lastIndexOf() method searches backwards, so position 15 means start the search at position 15, and search to the beginning.</p>

<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate", 15);
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>


Búsqueda de cadenas de JavaScript()

El método search() busca una cadena (o una expresión regular) y devuelve la posición del partido:

Ejemplos

let text = "Please locate where 'locate' occurs!";
text.search("locate");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The search() Method</h2>

<p>The search() method returns the position of the first occurrence of a string in a string.</p>
<p>The position of the first occurrence of "locate" is:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.search("locate");
document.getElementById("demo").innerHTML = index; 
</script>

</body>
</html>

let text = "Please locate where 'locate' occurs!";
text.search(/locate/);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The search() Method</h2>

<p>The search() method returns the position of the first occurrence of a string in a string.</p>
<p>Return the position of the first occurrence of a regular expression:</p>
<p id="demo"></p>

<script>
let text = "Please locate where 'locate' occurs!";
let index = text.search(/locate/);
document.getElementById("demo").innerHTML = index;
</script>

</body>
</html>


¿Te diste cuenta?

Los dos métodos, indexOf() y search(), ¿son iguales?

¿Aceptan los mismos argumentos (parámetros) y devuelven el mismo valor?

Los dos métodos NO son iguales. Estas son las diferencias:

  • El método search() no puede tomar un segundo argumento de posición inicial.

  • El método indexOf() no puede tomar potentes valores de búsqueda (expresiones regulares).

Aprenderás más sobre expresiones regulares en un capítulo posterior.



Coincidencia de cadenas de JavaScript()

El método match() devuelve una matriz que contiene los resultados de la coincidencia una cadena contra una cadena (o una expresión regular).

Ejemplos

Realice una búsqueda de "ain":

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match("ain"); 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain";
const myArr = text.match("ain");
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>

</body>
</html>

Realice una búsqueda de "ain":

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match(/ain/); 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain"; 
const myArr = text.match(/ain/);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;

</script>

</body>
</html>

Realice una búsqueda global de "ain":

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match(/ain/g); 

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a global search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain"; 
const myArr = text.match(/ain/g);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>

</body>
</html>

Realice una búsqueda global que no distinga entre mayúsculas y minúsculas de "ain":

let text = "The rain in SPAIN stays mainly in the plain"; 
text.match(/ain/gi);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The match() Method</h2>

<p>Perform a global, case-insensitive search for "ain":</p>

<p id="demo"></p>

<script>
let text = "The rain in SPAIN stays mainly in the plain"; 
const myArr = text.match(/ain/gi);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>

</body>
</html>

Nota

Si una expresión regular no incluye el modificador g (búsqueda global), match() devolverá solo la primera coincidencia en la cadena.

Lea más sobre expresiones regulares en el capítulo JS RegExp.


Coincidencia de cadena de JavaScriptTodo()

El método matchAll() devuelve un iterador que contiene los resultados de la coincidencia una cadena contra una cadena (o una expresión regular).

Ejemplo

const iterator = text.matchAll("Cats");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The matchAll() Method</h2>

<p>ES2020 intoduced the string method matchAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
const iterator = text.matchAll("Cats");

document.getElementById("demo").innerHTML = Array.from(iterator);
</script>

</body>
</html>

Si el parámetro es una expresión regular, se debe establecer el indicador global (g); de lo contrario Se lanza un TypeError.

Ejemplo

const iterator = text.matchAll(/Cats/g);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The matchAll() Method</h2>

<p>ES2020 intoduced the string method matchAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
const iterator = text.matchAll(/Cats/g);

document.getElementById("demo").innerHTML = Array.from(iterator);
</script>

</body>
</html>

Si desea buscar sin distinguir entre mayúsculas y minúsculas, se debe configurar el indicador de insensibilidad (i):

Ejemplo

const iterator = text.matchAll(/Cats/gi);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The matchAll() Method</h2>

<p>ES2020 intoduced the string method matchAll().</p>

<p id="demo"></p>

<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
const iterator = text.matchAll(/Cats/gi);

document.getElementById("demo").innerHTML = Array.from(iterator);
</script>

</body>
</html>

Notas

matchAll() es una característica de ES2020.

matchAll() no funciona en Internet Explorer.


La cadena JavaScript incluye()

El método includes() devuelve verdadero si una cadena contiene un valor específico.

De lo contrario, devuelve false.

Ejemplos

Compruebe si una cadena incluye "mundo":

let text = "Hello world, welcome to the universe.";
text.includes("world");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The includes() Method</h2>

<p>Check if a string includes "world":</p>
<p id="demo"></p>

<p>The includes() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world");
</script>

</body>
</html>

Compruebe si una cadena incluye "mundo". Comience en la posición 12:

let text = "Hello world, welcome to the universe.";
text.includes("world", 12);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The includes() Method</h2>

<p>Check if a string includes "world" starting from position 12:</p>
<p id="demo"></p>

<p>The includes() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world", 12);
</script>

</body>
</html>

Notas

includes() distingue entre mayúsculas y minúsculas.

includes() es una característica de ES6.

includes() no es compatible con Internet Explorer.


La cadena JavaScript comienza con()

El método startsWith() devuelve true si una cadena comienza con un valor específico.

De lo contrario, devuelve false:

Ejemplos

Devuelve verdadero:

let text = "Hello world, welcome to the universe.";
text.startsWith("Hello");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>
<p>Check if a string starts with "Hello":</p>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("Hello");
</script>

</body>
</html>

Devuelve falso:

let text = "Hello world, welcome to the universe.";
text.startsWith("world")

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world");
</script>

</body>
</html>

Se puede especificar una posición inicial para la búsqueda:

Devuelve falso:

let text = "Hello world, welcome to the universe.";
text.startsWith("world", 5)

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world", 5);
</script>

</body>
</html>

Devuelve verdadero:

let text = "Hello world, welcome to the universe.";
text.startsWith("world", 6)

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The startsWith() Method</h2>

<p id="demo"></p>

<p>The startsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world", 6);
</script>

</body>
</html>

Notas

startsWith() distingue entre mayúsculas y minúsculas.

startsWith() es una característica de ES6.

startsWith() no es compatible con Internet Explorer.


La cadena de JavaScript termina con()

El método endsWith() devuelve true si una cadena termina con un valor específico.

De lo contrario, devuelve false:

Ejemplos

Compruebe si una cadena termina con "Doe":

let text = "John Doe";
text.endsWith("Doe");

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Check if a string ends with "Doe":</p>

<p id="demo"></p>

<p>The endsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "John Doe";
document.getElementById("demo").innerHTML = text.endsWith("Doe");
</script>

</body>
</html>

Compruebe si los 11 primeros caracteres de una cadena terminan en "mundo":

let text = "Hello world, welcome to the universe.";
text.endsWith("world", 11);

Pruébelo usted mismo →

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Strings</h2>

<p>Check in the 11 first characters of a string ends with "world":</p>

<p id="demo"></p>

<p>The endsWith() method is not supported in Internet Explorer.</p>

<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.endsWith("world", 11);
</script>

</body>
</html>

Notas

endsWith() distingue entre mayúsculas y minúsculas.

endsWith() es una característica de ES6.

endsWith() no es compatible con Internet Explorer.


Referencia de cadena completa

Para obtener una referencia completa de cadenas, vaya a nuestro:

Referencia completa de cadenas de JavaScript.

La referencia contiene descripciones y ejemplos de todas las propiedades y métodos de cadena.