From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../reference/global_objects/string/index.html | 341 --------------------- 1 file changed, 341 deletions(-) delete mode 100644 files/ca/web/javascript/reference/global_objects/string/index.html (limited to 'files/ca/web/javascript/reference/global_objects/string/index.html') diff --git a/files/ca/web/javascript/reference/global_objects/string/index.html b/files/ca/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index b3b91b48d7..0000000000 --- a/files/ca/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,341 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -translation_of: Web/JavaScript/Reference/Global_Objects/String -original_slug: Web/JavaScript/Referencia/Objectes_globals/String ---- -
{{JSRef("Global_Objects", "String")}}
- -

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:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CodiSortida
\0el caràcter NUL
\'cometa simple
\"cometa doble
\\barra invertida
\nlínia nova
\rretorn de carro
\vbarra vertical
\ttabulador
\besborrar
\fform feed
\uXXXXcaràcter amb codificació unicode
\xXXcarà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 {{jsxref("String.length", "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 {{jsxref("String.prototype.indexOf()", "indexOf()")}}, o bé per a extreure substrings amb el mètode {{jsxref("String.prototype.substring()", "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 {{jsxref("String.prototype.charAt()", "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 {{jsxref("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 {{jsxref("String.prototype.localeCompare()", "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 {{jsxref("Global_Objects/Boolean", "Boolean")}} i {{jsxref("Global_Objects/Number", "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 {{jsxref("Operators/new", "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 {{jsxref("Global_Objects/eval", "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 {{jsxref("String.prototype.valueOf()", "valueOf()")}}.

- -
console.log(eval(s2.valueOf())); // escriu el nombre 4
-
- -
Nota: Per a una altra posible enfocament quant a string a JavaScript llegiu l'article sobre StringView — una representació de strings basada en arrays de tipatge explícit similar a C.
- -

Propietats

- -
-
{{jsxref("String.prototype")}}
-
Permet afegir propietats a un objecte String.
-
- -
{{jsOverrides("Function", "Properties", "prototype")}}
- -

Mètodes

- -
-
{{jsxref("String.fromCharCode()")}}
-
Retorna un string creat a partir de la seqüència de valors Unicode proporcionada.
-
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
-
Retorna un string creat a partir de la seqüència de code points proporcionada.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Retorna un string creat a partir de l'string proporcionat sense tindre en compte la codificació.
-
- -
{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint", "raw")}}
- -

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'));
-
- -

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} també estàn disponibles als mètodes de {{jsxref("Global_Objects/Array", "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

- -
{{page('/ca/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}
- -

Mètodes

- -

Mètodes no relacionats amb HTML

- -
{{page('/ca/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
- -

Mètodes d'embolcall de HTML

- -
{{page('/ca/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
- -

Exemples

- -

Exemple: Conversió de strings

- -

És posible utilitzar String com a una alternativa "més segura" de {{jsxref("String.prototype.toString()","toString()")}}, ja que tot i que normalment també crida el mètode toString() subjacent, també funciona per a {{jsxref("Global_Objects/null", "null")}} i {{jsxref("Global_Objects/undefined", "undefined")}}. Per exemple:

- -
var outputStrings = [];
-for (var i = 0, n = inputValues.length; i < n; ++i) {
-  outputStrings.push(String(inputValues[i]));
-}
-
- -

Especificacions

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificacióEstatComentari
ECMAScript 1a EdicióStandardDefinició inicial.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string-objects', 'String')}}{{Spec2('ES6')}} 
- -

Compatibilitat amb navegadors

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suport bàsic{{CompatChrome("0.2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suport bàsic{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Vegeu també

- - -- cgit v1.2.3-54-g00ecf