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 | 326 --------------------- .../global_objects/string/indexof/index.html | 191 ------------ .../global_objects/string/length/index.html | 125 -------- .../global_objects/string/trim/index.html | 139 --------- 4 files changed, 781 deletions(-) delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/length/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html (limited to 'files/pt-pt/web/javascript/reference/global_objects/string') diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index 4ccc8f5f81..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript 2015 - - JavaScript - - Referencia - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef}}
- -

O objeto global String é um construtor de strings ou sequência de carateres.

- -

Sintaxe

- -

Os literais de string assumem as formas:

- -
'string text'
-"string text"
-"中文 español English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ்"
- -

As Strings podem também ser criadas usando o objecto global string directamente:

- -
String(thing)
-new String(thing)
- -

Parâmetros

- -
-
thing
-
Qualquer parâmetro para ser convertido numa string.
-
- -

Strings modelo

- -

A partir de ECMAScript 2015, os literais de strings podem também ser chamados de Modelo strings:

- -
`hello world`
-`hello!
- world!`
-`hello ${who}`
-escape `<a>${who}</a>`
- -
-
- -

Notação Escape

- -

Além dos carateres regulares e imprmiveis, os carateres especiais também podem ser codificados com notação escape:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CódigoResultado
\XXX (XXX = 1 - 3 octal digits; range of 0 - 377)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
\'Aspas simples
\"Aspas duplas
\\Barra invertida
\nNova linha
\rcarriage return
\vTab vertical
\tTab
\bbackspace
\fform feed
\uXXXX (XXXX = 4 hex digits; range of 0x0000 - 0xFFFF)UTF-16 code unit / Unicode code point between U+0000 and U+FFFF
\u{X} ... \u{XXXXXX} (X…XXXXXX = 1 - 6 hex digits; range of 0x0 - 0x10FFFF)UTF-32 code unit / Unicode code point between U+0000 and U+10FFFF {{experimental_inline}}
\xXX (XX = 2 hex digits; range of 0x00 - 0xFF)ISO-8859-1 character / Unicode code point between U+0000 and U+00FF
- -
-

Note: Ao contrário de algumas outras linguagens, o Javascript não faz distinção entre strings com aspas simples e aspas duplas; Portanto a notação "escape" funciona em strings independente se foi utilizada aspas simples, ou aspas duplas na criação.

-
- -

Strings literais longas

- -

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

- -

You can use the + operator to append multiple strings together, like this:

- -
let longString = "This is a very long string which needs " +
-                 "to wrap across multiple lines because " +
-                 "otherwise my code is unreadable.";
-
- -

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

- -
let longString = "This is a very long string which needs \
-to wrap across multiple lines because \
-otherwise my code is unreadable.";
-
- -

Both of these result in identical strings being created.

- -

Descrição

- -

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

- -

Acesso de caráter

- -

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

- -
return 'cat'.charAt(1); // returns "a"
-
- -

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

- -
return 'cat'[1]; // returns "a"
-
- -

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

- -

Comparação de strings

- -

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

- -
var a = 'a';
-var b = 'b';
-if (a < b) { // true
-  console.log(a + ' is less than ' + b);
-} else if (a > b) {
-  console.log(a + ' is greater than ' + b);
-} else {
-  console.log(a + ' and ' + b + ' are equal.');
-}
-
- -

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

- -

Distinção entre string primitivas e objetos String

- -

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

- -

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

- -
var a = 'a';
-var b = 'b';
-if (a < b) { // true
-  console.log(a + ' is less than ' + b);
-} else if (a > b) {
-  console.log(a + ' is greater than ' + b);
-} else {
-  console.log(a + ' and ' + b + ' are equal.');
-}
-
- -

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

- -
-

Nota: a == b compares the strings in a and b for being equal in the usual case-sensitive way. If you wish to compare without regard to upper or lower case characters, use a function similar to this:

- -

function isEqual(str1, str2)
-     {
-     return str1.toUpperCase()===str2.toUpperCase();
-     } // isEqual

- -

Upper case is used instead of lower case in this function due to problems with certain UTF-8 character conversions.

-
- -

Distinção entre string primitivas e objetos String

- -

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

- -

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

- -
var s_prim = 'foo';
-var s_obj = new String(s_prim);
-
-console.log(typeof s_prim); // Logs "string"
-console.log(typeof s_obj);  // Logs "object"
-
- -

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

- -
var s1 = '2 + 2';             // creates a string primitive
-var s2 = new String('2 + 2'); // creates a String object
-console.log(eval(s1));        // returns the number 4
-console.log(eval(s2));        // returns the string "2 + 2"
-
- -

For these reasons, the code may break when it encounters String objects when it expects a primitive string instead, although generally, authors need not worry about the distinction.

- -

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

- -
console.log(eval(s2.valueOf())); // returns the number 4
-
- -
Nota: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
- -

Propriedades

- -
-
{{jsxref("String.prototype")}}
-
Allows the addition of properties to a String object.
-
- -

Métodos

- -
-
{{jsxref("String.fromCharCode()")}}
-
Returns a string created by using the specified sequence of Unicode values.
-
{{jsxref("String.fromCodePoint()")}}
-
Returns a string created by using the specified sequence of code points.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Returns a string created from a raw template string.
-
- -

Instâncias de String

- -

Propriedades

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

Métodos

- -

Methods unrelated to HTML

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

HTML wrapper methods

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

Exemplos

- -

Conversão de String

- -

It's possible to use String as a more reliable {{jsxref("String.prototype.toString()", "toString()")}} alternative, as it works when used on {{jsxref("null")}}, {{jsxref("undefined")}}, and on {{jsxref("Symbol", "symbols")}}. For example:

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

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.builtins.String",2)}}

- -

Consulte também:

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html deleted file mode 100644 index 721fb3c913..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/string/indexof/index.html +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: String.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/String/indexOf -tags: - - JavaScript - - Method - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf ---- -
{{JSRef}}
- -

O método indexOf() retorna o indíce da primeira ocorrência do valor especificado no objeto {{jsxref("String")}}, começando a procura a partir de fromIndex. Retorna -1 se o valor não for encontrado.

- -

Sintaxe

- -
str.indexOf(searchValue[, fromIndex])
- -

Parâmetros

- -
-
searchValue
-
Uma string com o valor pelo qual se procura.
-
fromIndex {{optional_inline}}
-
O ponto da string a partir do qual a procura deverá começar. Pode ter o valor de um qualquer inteiro. O valor por predefinição é 0. Se o fromIndex < 0 a procura é feita em toda a string (o mesmo que passar o valor 0). Se fromIndex >= str.length, o método retornará -1, exceção feita quando o valor de searchValue é uma string vazia, nesse caso retorna str.length.
-
- -

Descrição

- -

Os caractéres numa string são indexadas da esquerda para a direita. O índice do primeira caractér é 0, e o índice do último caractér da string, chamado de stringName, é stringName.length - 1.

- -
'Blue Whale'.indexOf('Blue');     // retorna  0
-'Blue Whale'.indexOf('Blute');    // retorna -1
-'Blue Whale'.indexOf('Whale', 0); // retorna  5
-'Blue Whale'.indexOf('Whale', 5); // retorna  5
-'Blue Whale'.indexOf('', 9);      // retorna  9
-'Blue Whale'.indexOf('', 10);     // retorna 10
-'Blue Whale'.indexOf('', 11);     // retorna 10
-
- -

Case-sensitivity

- -

O método indexOf() é sensível a maiúsculas e minúsculas. Por exemplo, a seguinte expressão retorna -1:

- -
'Blue Whale'.indexOf('blue'); // retorna -1
-
- -

Verificando ocorrências

- -

Repara que '0' não é avaliado como true e '-1' não é avaliado como false. Sendo assim, a forma correta de verificar se uma string específica existe dentro de outra string deverá ser:

- -
'Blue Whale'.indexOf('Blue') !== -1; // true
-'Blue Whale'.indexOf('Bloe') !== -1; // false
-
- -

Exemplos

- -

Usando indexOf() e lastIndexOf()

- -

O seguinte exemplo usa indexOf() e {{jsxref("String.prototype.lastIndexOf()", "lastIndexOf()")}} para localizar valores na string "Brave new world".

- -
var anyString = 'Brave new world';
-
-console.log('O índice do primeiro w desde o início é ' + anyString.indexOf('w'));
-// imprime 8
-console.log('O índice do primeiro w desde o fim é ' + anyString.lastIndexOf('w'));
-// imprime 10
-
-console.log('O índice de "new" desde o início é ' + anyString.indexOf('new'));
-// imprime 6
-console.log('O índice de "new" desde o fim é ' + anyString.lastIndexOf('new'));
-// imprime 6
-
- -

indexOf() e sensibilidade a maiúsculas e minúsculas

- -

O seguinte exemplo define duas variáveis do tipo string. As variáveis contêm a mesma string exceto o facto da segunda string conter as todas as letras maiúsculas. O primeiro método {{domxref("console.log()")}} apresenta 19. Mas porque o método indexOf() é sensível a maiúsculas e minúsculas, a string "cheddar" não é encontrada em myCapString, logo o segundo método console.log() apresenta -1.

- -
var myString    = 'brie, pepper jack, cheddar';
-var myCapString = 'Brie, Pepper Jack, Cheddar';
-
-console.log('myString.indexOf("cheddar") é ' + myString.indexOf('cheddar'));
-// imprime 19
-console.log('myCapString.indexOf("cheddar") é ' + myCapString.indexOf('cheddar'));
-// imprime -1
-
- -

Usando indexOf() para contar as ocorrências de uma letra numa string

- -

O seguinte exemplo atribuí à variável count o número de ocorrências da letra 'e' na string str:

- -
var str = 'To be, or not to be, that is the question.';
-var count = 0;
-var pos = str.indexOf('e');
-
-while (pos !== -1) {
-  count++;
-  pos = str.indexOf('e', pos + 1);
-}
-
-console.log(count); // imprime 4
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial.
{{SpecName('ES5.1', '#sec-15.5.4.7', 'String.prototype.indexOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.indexof', 'String.prototype.indexOf')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html deleted file mode 100644 index 7774170252..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/string/length/index.html +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: String.length -slug: Web/JavaScript/Reference/Global_Objects/String/length -tags: - - JavaScript - - Property - - Prototype - - Reference - - String -translation_of: Web/JavaScript/Reference/Global_Objects/String/length ---- -
{{JSRef}}
- -

A propriedade length representa o comprimento de uma string.

- -

Sintaxe

- -
str.length
- -

Descrição

- -

Esta propriedade retorna o número de code units na string. {{interwiki("wikipedia", "UTF-16")}}, o formato usado pelo JavaScript para a string, usa um single 16-bit code unit para representar os caracteres mais comuns, mas necessita de usar two code units para os caracteres menos comuns, pelo que é possível que o valor retornado por length não seja igual ao número de caracteres numa string.

- -

Para uma string vazia, length is 0.

- -

A propriedade estática (static) String.length retorna o valor 1.

- -

Exemplos

- -

Uso simples

- -
var x = 'Mozilla';
-var empty = '';
-
-console.log('Mozilla tem de tamanho ' + x.length + ' code units');
-/* "Mozilla tem de tamanho 7 code units" */
-
-console.log('Uma string vazia tem tamanho ' + empty.length);
-/* "Uma string vazia tem tamanho 0" */
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.5.1', 'String.prototype.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-string-instances-length', 'String.prototype.length')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html b/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html deleted file mode 100644 index 8ef29112f8..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/string/trim/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: String.prototype.trim() -slug: Web/JavaScript/Reference/Global_Objects/String/Trim -tags: - - ECMAScript 5 - - JavaScript - - Prototipo - - Referencia - - String - - metodo -translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim ---- -
{{JSRef}}
- -

O método trim() elimina espaço em branco de ambos os extremos dum string. Espaço em branco neste contexto são todos os caracteres que apenas representam espaço (espaço, tabulação, espaço fixo, etc.) e todos os caracteres que representam limites de linha (LF, CR, etc.).

- -

Sintaxe

- -
str.trim()
- -

Valor devolvido

- -

Um novo string que representa o string que chamou despojado do espaço em branco de ambos os extremos.

- -

Descrição

- -

O método trim() devolve o string despojado do espaço em branco de ambos os extremos. trim() não afecta o valor do string em si.

- -

Exemplos

- -

Using trim()

- -

O exemplo que se segue mostra o string 'foo' em minúsculas:

- -
var orig = '   foo  ';
-console.log(orig.trim()); // 'foo'
-
-// Outro exemplo de .trim() eliminando espaço em branco de apenas um lado.
-
-var orig = 'foo    ';
-console.log(orig.trim()); // 'foo'
-
- -

Polyfill

- -

Ao correr o código que se segue antes de qualquer outro criará trim() se não estiver nativamente disponível.

- -
if (!String.prototype.trim) {
-  String.prototype.trim = function () {
-    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
-  };
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES5.1', '#sec-15.5.4.20', 'String.prototype.trim')}}{{Spec2('ES5.1')}}Definição inicial. Implementada em JavaScript 1.8.1.
{{SpecName('ES6', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.trim', 'String.prototype.trim')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegadores

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

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