String length String slice() String substring() String substr() String replace() String replaceAll() String toUpperCase() String toLowerCase() String concat() String trim() String trimStart() String trimEnd() String padStart() String padEnd() String charAt() String charCodeAt() String split()
Los métodos de búsqueda de cadenas se tratan en el siguiente capítulo.
La propiedad longitud
devuelve la longitud de una cadena:
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The length Property</h2>
<p>The length of the string is:</p>
<p id="demo"></p>
<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>
</body>
</html>
Hay 3 métodos para extraer una parte de una cadena:
slice(start, end)
substring(start, end)
substr(start, length)
slice()
extrae una parte de una cadena y devuelve el parte extraída en una nueva cadena.
El método toma 2 parámetros: posición inicial y posición final (final no incluido).
Corta una porción de una cuerda desde la posición 7 a la posición 13:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>The sliced (extracted) part of the string is:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7,13);
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
JavaScript cuenta las posiciones desde cero.
La primera posición es 0.
La segunda posición es 1.
Si omites el segundo parámetro, el método cortará el resto de la cadena:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>Extract a part of a string from position 7:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7)
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
Si un parámetro es negativo, la posición se cuenta desde el final de la cadena:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>Extract a part of a string counting from the end:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
Este ejemplo corta una porción de una cadena desde la posición -12 a la posición -6:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12, -6);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The slice() Method</h2>
<p>Extract a part of a string and return the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12,-6)
document.getElementById("demo").innerHTML = part;
</script>
</body>
</html>
substring()
es similar a slice()
.
La diferencia es que los valores iniciales y finales menores que 0 se tratan como 0 en
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substring() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substring(7,13);
</script>
</body>
</html>
Si omite el segundo parámetro, substring()
eliminará el resto del cadena.
substr()
es similar a slice()
.
La diferencia es que el segundo parámetro especifica la longitud de la parte extraída.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string
and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7,6);
</script>
</body>
</html>
Si omite el segundo parámetro, substr()
eliminará el resto del cadena.
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7);
</script>
</body>
</html>
Si el primer parámetro es negativo, la posición cuenta desde el final del cadena.
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.substr(-4);
</script>
</body>
</html>
El método replace()
reemplaza un valor especificado por otro valor en una cadena:
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("Microsoft","W3Schools");
}
</script>
</body>
</html>
El método replace()
no cambia la cadena a la que se llama.
El método replace()
devuelve una nueva cadena.
El método replace()
reemplaza solo la primera coincidencia
Si desea reemplazar todas las coincidencias, utilice una expresión regular con el indicador /g configurado. Vea los ejemplos a continuación.
De forma predeterminada, el método replace()
reemplaza solo la primera coincidencia:
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft and Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("Microsoft","W3Schools");
}
</script>
</body>
</html>
De forma predeterminada, el método replace()
distingue entre mayúsculas y minúsculas. Escribiendo MICROSOFT (con mayúsculas) no funcionará:
let text = "Please visit Microsoft!";
let newText = text.replace("MICROSOFT", "W3Schools");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Try to replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("MICROSOFT","W3Schools");
}
</script>
<p>The replace() method is case sensitive. MICROSOFT (with upper-case) will not be replaced.</p>
</body>
</html>
Para reemplazar las mayúsculas y minúsculas, utilice una expresión regular con un indicador /i
(insensible):
let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "W3Schools");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace(/MICROSOFT/i,"W3Schools");
}
</script>
</body>
</html>
Las expresiones regulares se escriben sin comillas.
Para reemplazar todas las coincidencias, utilice una expresión regular con un indicador /g
(coincidencia global):
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Replace all occurrences of "Microsoft" with "W3Schools" in the paragraph below:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit Microsoft and Microsoft!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace(/Microsoft/g,"W3Schools");
}
</script>
</body>
</html>
Aprenderá mucho más sobre las expresiones regulares en el capítulo JavaScript Regular. Expresiones.
En 2021, JavaScript introdujo el método de cadena replaceAll()
:
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The replaceAll() Method</h2>
<p>ES2021 intoduced the string method replaceAll().</p>
<p id="demo"></p>
<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
El método replaceAll()
le permite especificar un expresión regular en lugar de una cadena que se va a reemplazar.
Si el parámetro es una expresión regular, se debe establecer el indicador global (g); de lo contrario Se lanza un TypeError.
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The replaceAll() Method</h2>
<p>ES2021 intoduced the string method replaceAll().</p>
<p id="demo"></p>
<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular";
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
replaceAll()
es una característica de ES2021.
replaceAll()
no funciona en Internet Explorer.
Una cadena se convierte a mayúsculas con toUpperCase()
:
Una cadena se convierte a minúsculas con toLowerCase()
:
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Convert string to upper case:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Hello World!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.toUpperCase();
}
</script>
</body>
</html>
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1
converted to lower
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Convert string to lower case:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo">Hello World!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.toLowerCase();
}
</script>
</body>
</html>
concat()
une dos o más cadenas:
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String</h1>
<h2>The concat() Method</h2>
<p>The concat() method joins two or more strings:</p>
<p id="demo"></p>
<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>
</body>
</html>
Se puede utilizar el método concat()
en lugar del operador más. Estas dos líneas hacen lo mismo:
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
Todos los métodos de cadena devuelven una nueva cadena. No modifican la cadena original.
Dijo formalmente:
Las cadenas son inmutables: las cadenas no se pueden cambiar, solo reemplazar.
El método trim()
elimina los espacios en blanco de ambos lados de una cadena:
let text1 = " Hello World! ";
let text2 = text1.trim();
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trim() Method</h2>
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trim();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
</body>
</html>
ECMAScript 2019 agregó el método String trimStart()
a JavaScript. <p>El método trimStart()
funciona como trim()
, pero elimina los espacios en blanco sólo desde el inicio de una cuerda.
let text1 = " Hello World! ";
let text2 = text1.trimStart();
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trimStart() Method</h2>
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trimStart();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
</body>
</html>
La cadena JavaScript trimStart()
es compatible con todos los navegadores modernos desde enero de 2020:
Chrome 66 | Edge 79 | Firefox 61 | Safari 12 | Opera 50 |
Apr 2018 | Jan 2020 | Jun 2018 | Sep 2018 | May 2018 |
ECMAScript 2019 agregó el método de cadena trimEnd()
a JavaScript. <p>El método trimEnd()
funciona como trim()
, pero elimina los espacios en blanco sólo al final de una cuerda.
let text1 = " Hello World! ";
let text2 = text1.trimEnd();
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The trimEnd() Method</h2>
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trimEnd();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
</body>
</html>
La cadena JavaScript trimEnd()
es compatible con todos los navegadores modernos desde enero de 2020:
Chrome 66 | Edge 79 | Firefox 61 | Safari 12 | Opera 50 |
Apr 2018 | Jan 2020 | Jun 2018 | Sep 2018 | May 2018 |
ECMAScript 2017 agregó dos nuevos métodos de cadena a JavaScript: padStart()
y padEnd()
para admitir el relleno al principio y al final de una cadena.
El método padStart()
rellena una cadena desde el principio.
Rellena una cuerda con otra cuerda (varias veces) hasta que alcanza una longitud determinada.
Rellene una cadena con "0" hasta que alcance la longitud 4:
let text = "5";
let padded = text.padStart(4,"0");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>
<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
text = text.padStart(4,"0");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Rellena una cuerda con "x" hasta que alcance la longitud 4:
let text = "5";
let padded = text.padStart(4,"x");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>
<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padStart(4,"x");
</script>
</body>
</html>
El método padStart()
es un método de cadena.
Para rellenar un número, primero convierta el número en una cadena.
Vea el ejemplo a continuación.
let numb = 5;
let text = numb.toString();
let padded = text.padStart(4,"0");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padStart() Method</h2>
<p>The padStart() method pads a string from the start.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padStart(4,0);
</script>
</body>
</html>
padStart()
es una característica de ECMAScript 2017.
Es compatible con todos los navegadores modernos:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
padStart()
no es compatible con Internet Explorer.
El método padEnd()
rellena una cadena desde el final.
Rellena una cuerda con otra cuerda (varias veces) hasta que alcanza una longitud determinada.
let text = "5";
let padded = text.padEnd(4,"0");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>
<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
text = text.padEnd(4,"0");
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
let text = "5";
let padded = text.padEnd(4,"x");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>
<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let text = "5";
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>
</body>
</html>
El método padEnd()
es un método de cadena.
Para rellenar un número, primero convierta el número en una cadena.
Vea el ejemplo a continuación.
let numb = 5;
let text = numb.toString();
let padded = text.padEnd(4,"0");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<h2>The padEnd() Method</h2>
<p>The padEnd() method pads a string at the end.</p>
<p>It pads the string with another string (multiple times) until it reaches a given length.</p>
<p id="demo"></p>
<script>
let numb = 5;
let text = numb.toString();
document.getElementById("demo").innerHTML = text.padEnd(4,"x");
</script>
</body>
</html>
padEnd()
es una característica de ECMAScript 2017.
Es compatible con todos los navegadores modernos:
Chrome | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
padEnd()
no es compatible con Internet Explorer.
Hay 3 métodos para extraer caracteres de cadena:
charAt(posición)
charCodeAt(posición)
Acceso a la propiedad [ ]
El método charAt()
devuelve el carácter en un punto especificado índice (posición) en una cadena:
let text = "HELLO WORLD";
let char = text.charAt(0);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String</h1>
<h2>The charAt() Method</h2>
<p>The charAt() method returns the character at a given position in a string:</p>
<p id="demo"></p>
<script>
var text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charAt(0);
</script>
</body>
</html>
El método charCodeAt()
devuelve el Unicode del carácter. en un índice especificado en una cadena:
El método devuelve un código UTF-16 (un número entero entre 0 y 65535).
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String</h1>
<h2>The charCodeAt() Method</h2>
<p>The charCodeAt() method returns the unicode of the character at a given position in a string:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text.charCodeAt(0);
</script>
</body>
</html>
ECMAScript 5 (2009) permite el acceso a la propiedad [] en cadenas:
let text = "HELLO WORLD";
let char = text[0];
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>Property access on strings:</p>
<p>The first character in the string is:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
document.getElementById("demo").innerHTML = text[0];
</script>
</body>
</html>
El acceso a la propiedad puede ser un poco impredecible:
Hace que las cadenas parezcan matrices (pero no lo son)
Si no se encuentra ningún carácter, [] devuelve indefinido, mientras que charAt() devuelve una cadena vacía.
Es de sólo lectura. str[0]="A" no da error (¡pero no funciona!)
let text = "HELLO WORLD";
text[0] = "A"; // Gives no error, but does not work
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>Property acces on strings are read only:</p>
<p id="demo"></p>
<script>
let text = "HELLO WORLD";
text[0] = "A"; // Does not work
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Si desea trabajar con una cadena como una matriz, puede convertirla en una matriz.
Una cadena se puede convertir en una matriz con el método split()
:
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<p>Display the first array element, after a string split:</p>
<p id="demo"></p>
<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[0];
</script>
</body>
</html>
Si se omite el separador, la matriz devuelta contendrá la cadena completa en el índice [0].
Si el separador es "", la matriz devuelta será una matriz de elementos únicos caracteres:
text.split("")
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript String Methods</h1>
<h2>The split().Method</h2>
<p id="demo"></p>
<script>
let text = "Hello";
const myArr = text.split("");
text = "";
for (let i = 0; i < myArr.length; i++) {
text += myArr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
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.