Este objeto nos permite manipular diferentes tipos de cadenas para facilitar su trabajo. Cuando asignamos una cadena a una variable, JS crea un objeto de tipo String; Esto nos permite hacer manipulaciones.
var carname="Volvo XC60";
var carname='Volvo XC60';
Cada carácter de cadena se puede acceder por su valor de ubicación (índice):
var character=carname[7];
Las citas se pueden colocar dentro de la cadena:
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
O pueden colocarse entre comillas dentro de la cadena \ usando el carácter sombra:
var answer='It\'s alright';
var answer="He is called \"Johnny\"";
var txt="Hello World!";
document.write(txt.length);
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
Si no fuera un texto de búsqueda, devolvería el valor -1.
match() metodo
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
replace() El método reemplaza una cadena por otra.
str="Please visit Microsoft!"
var n=str.replace("Microsoft","W3Schools");
toUpperCase() / toLowerCase():
var txt="Hello World!"; // String
var txt1=txt.toUpperCase(); // txt1 is txt converted to upper
var txt2=txt.toLowerCase(); // txt2 is txt converted to lower
split():
txt="a,b,c,d,e" // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
Barra invertida (\) Aprueba apóstrofes, nuevas líneas, comillas y otros caracteres especiales.
String mal utilizado:
var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
Bien utilizado:
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);
Otros caracteres especiales:
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
var carname = "Volvo XC60";
var carname = 'Volvo XC60';
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
The length of a string is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Because strings must be written within quotes, JavaScript will misunderstand this string:
var y = "We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the \ escape character.
The backslash escape character turns special characters into string characters:
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
The escape character (\) can also be used to insert other special characters in a string.
This is the lists of special characters that can be added to a text string with the backslash sign:
For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it, is after an operator:
document.getElementById("demo").innerHTML =
"Hello Dolly.";
You can also break up a code line within a text string with a single backslash:
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
However, you cannot break up a code line with a backslash:
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
Normally, JavaScript strings are primitive values, created from literals: var firstName = "John"
But strings can also be defined as objects with the keyword new: var firstName = new String("John")
var x = "John";
var y = new String("John");
// type of x will return String
// type of y will return Object
Don't create strings as objects. They slow down execution speed, and produce nasty side effects:
var x = "John";
var y = new String("John");
// (x === y) is now false because x is a string and y is an object.
Primitive values, like "John Doe", cannot have properties or methods (because they are not objects).
But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.
String methods are covered in next chapter.
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
var str = "Please locate where 'locate' occurs!";
var pos = str.lastIndexOf("locate");
Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found.
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
Both methods accept a second parameter as the starting position for the search.
The search() method searches a string for a specified value and returns the position of the match:
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
The two methods, indexOf() and search(), are equal.
They accept the same arguments (parameters), and they return the same value.
The two methods are equal, but the search() method can take much more powerful search values.
You will learn more about powerful search values in the chapter about regular expressions.
There are 3 methods for extracting a part of a string:
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the starting index (position), and the ending index (position).
This example slices out a portion of a string from position 7 to position 13:
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13);
The result of res will be:
Banana
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12,-6);
The result of res will be:
Banana
If you omit the second parameter, the method will slice out the rest of the string:
var res = str.slice(7);
or, counting from the end:
var res = str.slice(-12);
Negative positions does not work in Internet Explorer 8 and earlier.
substring() is similar to slice().
The difference is that substring() cannot accept negative indexes.
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
The result of res will be:
Banana
If you omit the second parameter, substring() will slice out the rest of the string.
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
var str = "Apple, Banana, Kiwi";
var res = str.substr(7,6);
The result of res will be:
Banana
If the first parameter is negative, the position counts from the end of the string.
The second parameter can not be negative, because it defines the length.
If you omit the second parameter, substr() will slice out the rest of the string.
The replace() method replaces a specified value with another value in a string:
str = "Please visit Microsoft!";
var n = str.replace("Microsoft","W3Schools");
The replace() method can also take a regular expression as the search value.
A string is converted to upper case with toUpperCase():
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase():
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
concat() joins two or more strings:
var text1 = "Hello";
var text2 = "World";
text3 = text1.concat(" ",text2);
The concat() method can be used instead of the plus operator. These two lines do the same:
var text = "Hello" + " " + "World!";
var text = "Hello".concat(" ","World!");
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
There are 2 safe methods for extracting string characters:
The charAt() method returns the character at a specified index (position) in a string:
var str = "HELLO WORLD";
str.charAt(0); // returns H
The charCodeAt() method returns the unicode of the character at a specified index in a string:
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
You might have seen code like this, accessing a string as an array:
var str = "HELLO WORLD";
str[0]; // returns H
This is unsafe and unpredictable:
If you want to read a string as an array, convert it to an array first.
A string can be converted to an array with the split() method:
var txt = "a,b,c,d,e"; // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters:
var txt = "Hello"; // String
txt.split(""); // Split in characters
For a complete reference, go to our Complete JavaScript String Reference.
The reference contains descriptions and examples of all string properties and methods.