This article is in need of a technical review.
This article is in need of an editorial review.
Resum
L'objecte global String és un constructor per a strings, també conegudes com a cadenes de caràcters.
Sintaxi
Els literals de tipus Stringpoden tenir les següents formes:
'string text' "string text" "中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어தமிழ்"
A més dels caràcters imprimibles normals, es poden codificar caràcters especials mitjançant la notació d'escapament:
| Codi | Sortida |
|---|---|
\0 |
el caràcter NUL |
\' |
cometa simple |
\" |
cometa doble |
\\ |
barra invertida |
\n |
línia nova |
\r |
retorn de carro |
\v |
barra vertical |
\t |
tabulador |
\b |
esborrar |
\f |
form feed |
\uXXXX |
caràcter amb codificació unicode |
\xXX |
caràcter amb codificació Latin-1 |
O bé utilitzant l'objecte global String de forma directa:
String(quelcom)
new String(quelcom)
Paràmetres
quelcom- Qualsevol cosa que serà convertida a string.
Descripció
Les Strings són útils per a emmagatzemar dades que poden ser representades en forma de texte. Algunes de les operacions més emprades en strings són per a obtindre la seva llargada length, per a concatenar-les mitjançant els operadors de strings + i +=, per a comprovar l'existència o localització de substrings amb el mètode indexOf(), o bé per a extreure substrings amb el mètode substring().
Accés als caràcters
Hi ha dues formes d'accedir a un caràcter individual emmagatzemat dins un string. El primer és el mètode charAt():
return 'cat'.charAt(1); // retorna "a"
L'altra forma (introduida a ECMAScript 5) és fer anar l'string com si fós un objecte de tipus array, on els caràcters individuals es corresponen a un índex numèric:
return 'cat'[1]; // retorna "a"
Utilitzar la notació de claus per a esborrar o bé assignar un valor a un caràcter no funcionarà. Les propietats involucrades no són de tipus no-escriptura i no són configurables. (Vegeu Object.defineProperty() per a més informació).
Comparar strings
Els desenvolupadors de C disposen de la funció strcmp() per a comparar strings. A JavaScript senzillament es poden utilitzar els operadors major-que i menor-que
var a = 'a';
var b = 'b';
if (a < b) { // true
print(a + ' és menor que ' + b);
} else if (a > b) {
print(a + ' és major que ' + b);
} else {
print(a + ' i ' + b + ' són iguals.');
}
Es pot obtindre un resultat similar mitjançant el mètode localeCompare(), heredat per les instàncies de String.
Distinció entre les primitives string i els objectes String
Cal recalcar que JavaScript distingeix entre objectes de tipus String i valors primitius de tipus string (El mateix succeeix amb Boolean i Numbers
Els literals de tipus string (englobats en cometes simples o dobles) així com strings retornats per crides a l'objecte String en un contexte no constructor (és a dir, sense utilitzar la paraula clau new) són strings primitives. JavaScript automàticament converteix primitives a objectes String, de forma que és posible utilitzar mètodes de l'objecte String en strings primitives. En els contextes on s'ha d'invocar un mètode en una primitiva string o es demana la una propietat, JavaScript automàticament embolcallarà la primitiva string amb un objecte String i cridarà el mètode o la propietat corresponent.
var s_prim = 'foo'; var s_obj = new String(s_prim); console.log(typeof s_prim); // Escriu "string" console.log(typeof s_obj); // Escriu "object"
Les primitives string i els objectes String també donen resultats diferents a l'utilitzar eval(). Les primitives passades a eval són considerades codi font; els objectes String es tracten com qualsevol altre objecte, és a dir, retornan l'objecte. Per exemple:
var s1 = '2 + 2'; // crea una primitiva string
var s2 = new String('2 + 2'); // crea un objecte String
console.log(eval(s1)); // escriu el nombre 4
console.log(eval(s2)); // escriu la string "2 + 2"
És per aquestes raons que el codi pot produïr errors quan trobi objectes String però s'esperès una primitiva string, tot i que de forma general els autors no s'han de preocupar per la distinció.
Un objecte String sempre es pot convertir en la seva representació primitiva mitjançant el mètode valueOf().
console.log(eval(s2.valueOf())); // escriu el nombre 4
StringView — una representació de strings basada en arrays de tipatge explícit similar a C.Propietats
String instances, see Properties of String instances.String.prototype- Permet afegir propietats a un objecte
String.
Mètodes
String instances, see Methods of String instances.String.fromCharCode()- Retorna un string creat a partir de la seqüència de valors Unicode proporcionada.
String.fromCodePoint()- Retorna un string creat a partir de la seqüència de code points proporcionada.
String.raw()- Retorna un string creat a partir de l'string proporcionat sense tindre en compte la codificació.
Mètodes genèrics de String
Els mètodes de les instàncies de String també estan disponibles a Firefox a partir del JavaScript 1.6 (tot i que no formen part de l'standard ECMAScript) a l'objecte String, així es poden aplicar els mètodes de String a qualsevol objecte:
var num = 15; console.log(String.replace(num, /5/, '2'));
Generics també estàn disponibles als mètodes de Array.
A continuació es mostra un shim per a donar suport als navegadors que no ho suporten:
/*globals define*/
// Assumes all supplied String instance methods already present
// (one may use shims for these if not available)
(function() {
'use strict';
var i,
// We could also build the array of methods with the following, but the
// getOwnPropertyNames() method is non-shimable:
// Object.getOwnPropertyNames(String).filter(function(methodName) {
// return typeof String[methodName] === 'function';
// });
methods = [
'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
'toLocaleUpperCase', 'localeCompare', 'match', 'search',
'replace', 'split', 'substr', 'concat', 'slice'
],
methodCount = methods.length,
assignStringGeneric = function(methodName) {
var method = String.prototype[methodName];
String[methodName] = function(arg1) {
return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
};
};
for (i = 0; i < methodCount; i++) {
assignStringGeneric(methods[i]);
}
}());
Instàncies de String
Propietats
String.prototype.constructor- Specifies the function that creates an object's prototype.
String.prototype.length- Reflects the length of the string.
N- Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value of
length. These properties are read-only.
Mètodes
Mètodes no relacionats amb HTML
String.prototype.charAt()- Returns the character at the specified index.
String.prototype.charCodeAt()- Returns a number indicating the Unicode value of the character at the given index.
String.prototype.codePointAt()- Returns a non-negative integer that is the UTF-16 encoded code point value at the given position.
String.prototype.concat()- Combines the text of two strings and returns a new string.
String.prototype.includes()- Determines whether one string may be found within another string.
String.prototype.endsWith()- Determines whether a string ends with the characters of another string.
String.prototype.indexOf()- Returns the index within the calling
Stringobject of the first occurrence of the specified value, or -1 if not found. String.prototype.lastIndexOf()- Returns the index within the calling
Stringobject of the last occurrence of the specified value, or -1 if not found. String.prototype.localeCompare()- Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
String.prototype.match()- Used to match a regular expression against a string.
String.prototype.normalize()- Returns the Unicode Normalization Form of the calling string value.
String.prototype.quote()Wraps the string in double quotes (""").String.prototype.repeat()- Returns a string consisting of the elements of the object repeated the given times.
String.prototype.replace()- Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
String.prototype.search()- Executes the search for a match between a regular expression and a specified string.
String.prototype.slice()- Extracts a section of a string and returns a new string.
String.prototype.split()- Splits a
Stringobject into an array of strings by separating the string into substrings. String.prototype.startsWith()- Determines whether a string begins with the characters of another string.
String.prototype.substr()- Returns the characters in a string beginning at the specified location through the specified number of characters.
String.prototype.substring()- Returns the characters in a string between two indexes into the string.
String.prototype.toLocaleLowerCase()- The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as
toLowerCase(). String.prototype.toLocaleUpperCase()- The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as
toUpperCase(). String.prototype.toLowerCase()- Returns the calling string value converted to lower case.
String.prototype.toSource()- Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the
Object.prototype.toSource()method. String.prototype.toString()- Returns a string representing the specified object. Overrides the
Object.prototype.toString()method. String.prototype.toUpperCase()- Returns the calling string value converted to uppercase.
String.prototype.trim()- Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
String.prototype.trimLeft()- Trims whitespace from the left side of the string.
String.prototype.trimRight()- Trims whitespace from the right side of the string.
String.prototype.valueOf()- Returns the primitive value of the specified object. Overrides the
Object.prototype.valueOf()method. String.prototype[@@iterator]()- Returns a new
Iteratorobject that iterates over the code points of a String value, returning each code point as a String value.
Mètodes d'embolcall de HTML
These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.
String.prototype.anchor()<a name="name">(hypertext target)String.prototype.big()<big>String.prototype.blink()<blink>String.prototype.bold()<b>String.prototype.fixed()<tt>String.prototype.fontcolor()<font color="color">String.prototype.fontsize()<font size="size">String.prototype.italics()<i>String.prototype.link()<a href="/old?u=https%3A%2F%2Fdeveloper.mozilla.org%2Fca%2Fdocs%2FWeb%2FJavaScript%2FReferencia%2FObjectes_globals%2Frul&y=1999">(link to URL)String.prototype.small()<small>String.prototype.strike()<strike>String.prototype.sub()<sub>String.prototype.sup()<sup>
Exemples
Exemple: Conversió de strings
És posible utilitzar String com a una alternativa "més segura" de toString(), ja que tot i que normalment també crida el mètode toString() subjacent, també funciona per a null i undefined. Per exemple:
var outputStrings = [];
for (var i = 0, n = inputValues.length; i < n; ++i) {
outputStrings.push(String(inputValues[i]));
}
Especificacions
| Especificació | Estat | Comentari |
|---|---|---|
| ECMAScript 1a Edició | Standard | Definició inicial. |
| ECMAScript 5.1 (ECMA-262) The definition of 'String' in that specification. |
Standard | |
| ECMAScript 6 (ECMA-262) The definition of 'String' in that specification. |
Release Candidate |
Compatibilitat amb navegadors
| Característica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Suport bàsic | 0.2 | (Yes) | (Yes) | (Yes) | (Yes) |
| Característica | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Suport bàsic | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |