Las cadenas de JavaScript sirven para almacenar y manipular texto.
Una cadena de JavaScript tiene cero o más caracteres escritos entre comillas.
let text = "John Doe";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p id="demo"></p>
<script>
let text = "John Doe"; // String written inside quotes
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Puede utilizar comillas simples o dobles:
let carName1 = "Volvo XC60";
// Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>Strings are written inside quotes. You can use single or double quotes:</p>
<p id="demo"></p>
<script>
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
document.getElementById("demo").innerHTML =
carName1 + " " + carName2;
</script>
</body>
</html>
Puedes usar comillas dentro de una cadena, siempre y cuando no coincidan con las comillas. rodeando la cuerda:
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>You can use quotes inside a string, as long as they don't match the quotes surrounding the string.</p>
<p id="demo"></p>
<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
document.getElementById("demo").innerHTML =
answer1 + "<br>" + answer2 + "<br>" + answer3;
</script>
</body>
</html>
Para encontrar la longitud de una cadena, use la propiedad incorporada length
:
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>
Debido a que las cadenas deben escribirse entre comillas, JavaScript malinterpretará esta cadena:
let text = "We are the so-called "Vikings" from the north.";
La cadena se cortará a "Somos los llamados".
La solución para evitar este problema es utilizar el carácter de escape de barra invertida.
El carácter de escape de barra invertida (\
) convierte caracteres especiales en caracteres de cadena:
Code | Result | Description |
---|---|---|
\' | ' | Single quote |
\" | " | Double quote |
\\ | \ | Backslash |
La secuencia \"
inserta una comilla doble en una cadena:
let text = "We are the so-called \"Vikings\" from the north.";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>The escape sequence \" inserts a double quote in a string.</p>
<p id="demo"></p>
<script>
let text = "We are the so-called \"Vikings\" from the north.";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
La secuencia \'
inserta una comilla simple en una cadena:
let text= 'It\'s alright.';
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>The escape sequence \' inserts a single quote in a string.</p>
<p id="demo"></p>
<script>
let text = 'It\'s alright.';
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
La secuencia \\
inserta una barra invertida en una cadena:
let text = "The character \\ is called backslash.";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>The escape sequence \\ inserts a backslash in a string.</p>
<p id="demo"></p>
<script>
let text = "The character \\ is called backslash.";
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Otras seis secuencias de escape son válidas en JavaScript:
Retroceso
Avance de formulario
Nueva línea
Retorno de carro
Tabulador horizontal
Tabulador vertical
Los 6 personajes de escape anteriores fueron diseñados originalmente para controlar máquinas de escribir, teletipos y faxes. No tienen ningún sentido en HTML.
Para una mejor legibilidad, a los programadores les gusta evitar líneas de código más largas que 80 caracteres.
Si una declaración de JavaScript no cabe en una línea, el mejor lugar para dividirla es después de un operador:
document.getElementById("demo").innerHTML =
"Hello Dolly!";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>
The best place to break a code line is after an operator or a comma.
</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"Hello Dolly!";
</script>
</body>
</html>
También puedes dividir una línea de código dentro de una cadena de texto con una sola barra invertida:
document.getElementById("demo").innerHTML =
"Hello \
Dolly!";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>
You can break a code line within a text string with a backslash.
</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
</script>
</body>
</html>
El método \
no es el método preferido. Es posible que no tenga soporte universal.
Algunos navegadores sí lo tienen. No permita espacios detrás del carácter \
.
Una forma más segura de romper una cuerda es usar una cuerda suma:
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p>The safest way to break a code line in a string is using string addition.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
</script>
</body>
</html>
No puedes dividir una línea de código con una barra invertida:
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p id="demo">You cannot break a code line with a \ backslash.</p>
<script>
document.getElementById("demo").innerHTML = \
"Hello Dolly.";
</script>
</body>
</html>
Normalmente, las cadenas de JavaScript son valores primitivos, creados a partir de literales:
let x = "John";
Pero las cadenas también se pueden definir como objetos con la palabra clave new
:
let y = new String("John");
let x = "John";
let y = new String("John");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Strings</h1>
<p id="demo"></p>
<script>
// x is a string
let x = "John";
// y is an object
let y = new String("John");
document.getElementById("demo").innerHTML =
typeof x + "<br>" + typeof y;
</script>
</body>
</html>
No cree objetos Strings.
La palabra clave new
complica el código y ralentiza la velocidad de ejecución.
Los objetos de cadena pueden producir resultados inesperados:
Cuando se utiliza el operador ==
, x e y son iguales:
let x = "John";
let y = new String("John");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Never Create Strings as Objects</h2>
<p>Strings and objects cannot be safely compared.</p>
<p id="demo"></p>
<script>
let x = "John"; // x is a string
let y = new String("John"); // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>
</body>
</html>
Cuando se utiliza el operador ===
, x e y no son iguales:
let x = "John";
let y = new String("John");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Never Create Strings as Objects</h2>
<p>Strings and objects cannot be safely compared.</p>
<p id="demo"></p>
<script>
let x = "John"; // x is a string
let y = new String("John"); // y is an object
document.getElementById("demo").innerHTML = (x===y);
</script>
</body>
</html>
Tenga en cuenta la diferencia entre (x==y)
y (x===y)
.
(x == y)
¿verdadero o falso?
let x = new String("John");
let y = new String("John");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Never Create Strings as Objects</h2>
<p>JavaScript objects cannot be compared.</p>
<p id="demo"></p>
<script>
let x = new String("John"); // x is an object
let y = new String("John"); // y is an object
document.getElementById("demo").innerHTML = (x==y);
</script>
</body>
</html>
(x === y)
¿verdadero o falso?
let x = new String("John");
let y = new String("John");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>Never Create Strings as Objects</h2>
<p>JavaScript objects cannot be compared.</p>
<p id="demo"></p>
<script>
let x = new String("John"); // x is an object
let y = new String("John"); // y is an object
document.getElementById("demo").innerHTML = (x===y);
</script>
</body>
</html>
La comparación de dos objetos JavaScript siempre devuelve falso.
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.