diff --git a/1-js/05-data-types/03-string/1-ucfirst/solution.md b/1-js/05-data-types/03-string/1-ucfirst/solution.md
index be5dd2aaf..4c046de61 100644
--- a/1-js/05-data-types/03-string/1-ucfirst/solution.md
+++ b/1-js/05-data-types/03-string/1-ucfirst/solution.md
@@ -1,14 +1,14 @@
-We can't "replace" the first character, because strings in JavaScript are immutable.
+Não podemos "substituir" o primeiro caractere, pois strings em JavaScript são imutáveis.
-But we can make a new string based on the existing one, with the uppercased first character:
+Mas podemos fazer uma nova string baseando-se na existente, com o primeiro caractere em maiúsculo:
```js
let newStr = str[0].toUpperCase() + str.slice(1);
```
-There's a small problem though. If `str` is empty, then `str[0]` is `undefined`, and as `undefined` doesn't have the `toUpperCase()` method, we'll get an error.
+Entretanto, tem um pequeno problema. Se `str` está vazio, então `str[0]` é `undefined`, e como `undefined` não possui o método `toUpperCase()` teremos um erro.
-The easiest way out is to add a test for an empty string, like this:
+A maneira mais fácil de contornar é adicionar um teste para string vazia, algo assim:
```js run demo
function ucFirst(str) {
diff --git a/1-js/05-data-types/03-string/1-ucfirst/task.md b/1-js/05-data-types/03-string/1-ucfirst/task.md
index ed8a1e6a7..5661a9082 100644
--- a/1-js/05-data-types/03-string/1-ucfirst/task.md
+++ b/1-js/05-data-types/03-string/1-ucfirst/task.md
@@ -1,10 +1,10 @@
-importance: 5
+importância: 5
---
-# Uppercase the first character
+# Transforme o primeiro caractere em maiúsculo
-Write a function `ucFirst(str)` that returns the string `str` with the uppercased first character, for instance:
+Escreva uma função `ucFirst(str)` que retorna a string `str` com o primeiro caractere em maiúsculo, por exemplo:
```js
ucFirst("john") == "John";
diff --git a/1-js/05-data-types/03-string/2-check-spam/solution.md b/1-js/05-data-types/03-string/2-check-spam/solution.md
index de8dde57d..1ae6a3040 100644
--- a/1-js/05-data-types/03-string/2-check-spam/solution.md
+++ b/1-js/05-data-types/03-string/2-check-spam/solution.md
@@ -1,4 +1,4 @@
-To make the search case-insensitive, let's bring the string to lower case and then search:
+Para fazer a procura insensível a maiúsculas e minúsculas vamos transformar a string em minúsculas e então procurar:
```js run demo
function checkSpam(str) {
diff --git a/1-js/05-data-types/03-string/2-check-spam/task.md b/1-js/05-data-types/03-string/2-check-spam/task.md
index 98b5dd8a0..204db3ca2 100644
--- a/1-js/05-data-types/03-string/2-check-spam/task.md
+++ b/1-js/05-data-types/03-string/2-check-spam/task.md
@@ -1,12 +1,12 @@
-importance: 5
+importânica: 5
---
-# Check for spam
+# Checagem de spam
-Write a function `checkSpam(str)` that returns `true` if `str` contains 'viagra' or 'XXX', otherwise `false`.
+Escreva uma função `checkSpam(str)` que retorna `true` se `str` contém 'viagra' ou 'XXX', caso contrário, `false`.
-The function must be case-insensitive:
+A função deve ser insensível a maiúsculas e minúsculas:
```js
checkSpam('buy ViAgRA now') == true
diff --git a/1-js/05-data-types/03-string/3-truncate/solution.md b/1-js/05-data-types/03-string/3-truncate/solution.md
index d51672ae6..2cf381304 100644
--- a/1-js/05-data-types/03-string/3-truncate/solution.md
+++ b/1-js/05-data-types/03-string/3-truncate/solution.md
@@ -1,6 +1,6 @@
-The maximal length must be `maxlength`, so we need to cut it a little shorter, to give space for the ellipsis.
+O tamanho máximo deve ser `maxlength`, então precisamos cortar a string um pouco para dar espaço à reticências.
-Note that there is actually a single Unicode character for an ellipsis. That's not three dots.
+Note que há apenas um único caractere Unicode para reticências. Não são três pontos.
```js run demo
function truncate(str, maxlength) {
diff --git a/1-js/05-data-types/03-string/3-truncate/task.md b/1-js/05-data-types/03-string/3-truncate/task.md
index c99a5f15a..4056c6899 100644
--- a/1-js/05-data-types/03-string/3-truncate/task.md
+++ b/1-js/05-data-types/03-string/3-truncate/task.md
@@ -1,14 +1,14 @@
-importance: 5
+importância: 5
---
-# Truncate the text
+# Cortar o texto
-Create a function `truncate(str, maxlength)` that checks the length of the `str` and, if it exceeds `maxlength` -- replaces the end of `str` with the ellipsis character `"…"`, to make its length equal to `maxlength`.
+Crie uma função `truncate(str, maxlength)` que checa se o tamanho do `str` e, se exceder `maxlength` -- substitua o fim de `str` com o caractere de reticências `"…"`, para fazer seu tamanho igual ao `maxlength`.
-The result of the function should be the truncated (if needed) string.
+O resultado da função deve ser a string cortada(se necessário).
-For instance:
+Por exemplo:
```js
truncate("What I'd like to tell on this topic is:", 20) == "What I'd like to te…"
diff --git a/1-js/05-data-types/03-string/4-extract-currency/task.md b/1-js/05-data-types/03-string/4-extract-currency/task.md
index feb16e642..4d08e7858 100644
--- a/1-js/05-data-types/03-string/4-extract-currency/task.md
+++ b/1-js/05-data-types/03-string/4-extract-currency/task.md
@@ -2,13 +2,13 @@ importance: 4
---
-# Extract the money
+# Extraia o dinheiro
-We have a cost in the form `"$120"`. That is: the dollar sign goes first, and then the number.
+Temos um custo no formato `"$120"`.Isso é: o cifrão aparece primeiro e depois o número.
-Create a function `extractCurrencyValue(str)` that would extract the numeric value from such string and return it.
+Crie uma função `extractCurrencyValue(str)` que extraia o valor numérico da string e o retorne.
-The example:
+O exemplo:
```js
alert( extractCurrencyValue('$120') === 120 ); // true
diff --git a/1-js/05-data-types/03-string/article.md b/1-js/05-data-types/03-string/article.md
index 60ce2b6f0..e208cbf0a 100644
--- a/1-js/05-data-types/03-string/article.md
+++ b/1-js/05-data-types/03-string/article.md
@@ -1,23 +1,23 @@
# Strings
-In JavaScript, the textual data is stored as strings. There is no separate type for a single character.
+Em JavaScript, os dados textuais são armazenados como strings. Não há um tipo separado para um único caractere.
-The internal format for strings is always [UTF-16](https://en.wikipedia.org/wiki/UTF-16), it is not tied to the page encoding.
+O formato interno para strings é sempre [UTF-16](https://en.wikipedia.org/wiki/UTF-16), isso não está relacionado com a codificação da página.
-## Quotes
+## Aspas
-Let's recall the kinds of quotes.
+Vamos recapitular os tipos de aspas.
-Strings can be enclosed within either single quotes, double quotes or backticks:
+Strings podem ser delimitadas por aspas simples, aspas duplas ou crases (acento grave):
```js
-let single = 'single-quoted';
-let double = "double-quoted";
+let single = 'aspas simples';
+let double = "aspas duplas";
-let backticks = `backticks`;
+let backticks = `crases`;
```
-Single and double quotes are essentially the same. Backticks, however, allow us to embed any expression into the string, by wrapping it in `${…}`:
+Aspas simples e duplas são essencialmente a mesma coisa. Crases, no entanto, nos permite incorporar (interpolar) qualquer expressão na string, colocando-a dentro de `${…}`:
```js run
function sum(a, b) {
@@ -27,7 +27,7 @@ function sum(a, b) {
alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3.
```
-Another advantage of using backticks is that they allow a string to span multiple lines:
+Outra vantagem de usar crases é que elas permitem que uma string ocupe múltiplas linhas:
```js run
let guestList = `Guests:
@@ -36,118 +36,118 @@ let guestList = `Guests:
* Mary
`;
-alert(guestList); // a list of guests, multiple lines
+alert(guestList); // uma lista de convidados, múltiplas linhas
```
-Looks natural, right? But single or double quotes do not work this way.
+Parece natural, certo? Mas aspas simples ou duplas não funcionam dessa maneira.
-If we use them and try to use multiple lines, there'll be an error:
+Se nós as usarmos e tentarmos utilizar múltiplas linhas, haverá um erro:
```js run
let guestList = "Guests: // Error: Unexpected token ILLEGAL
* John";
```
-Single and double quotes come from ancient times of language creation, when the need for multiline strings was not taken into account. Backticks appeared much later and thus are more versatile.
+Aspas simples e duplas vêm de tempos antigos da criação da linguagem, quando a necessidade por strings em múltiplas linhas não era levada em conta. Crases surgiram bem mais tarde e, assim, são mais versáteis.
-Backticks also allow us to specify a "template function" before the first backtick. The syntax is: func`string`. The function `func` is called automatically, receives the string and embedded expressions and can process them. This feature is called "tagged templates", it's rarely seen, but you can read about it in the MDN: [Template literals](mdn:/JavaScript/Reference/Template_literals#Tagged_templates).
+Crases também nos permite especificar uma "template function" antes da primeira crase. A sintaxe é: func`string`. A função `func` é chamada automaticamente, recebe a string e as expressões incorporadas e pode as processar. Esse recurso é chamado de "tagged templates", raramente visto, mas você pode ler mais sobre em MDN: [Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals).
-## Special characters
+## Caracteres especiais
-It is still possible to create multiline strings with single and double quotes by using a so-called "newline character", written as `\n`, which denotes a line break:
+Ainda é possível criar strings em múltiplas linhas com aspas simples e duplas apenas usando o chamado "caractere de nova linha", escrito como `\n`, que representa uma quebra de linha:
```js run
let guestList = "Guests:\n * John\n * Pete\n * Mary";
-alert(guestList); // a multiline list of guests, same as above
+alert(guestList); // uma lista de convidados em múltiplas linhas, como acima
```
-As a simpler example, these two lines are equal, just written differently:
+Como um exemplo simplório, estas duas linhas são iguais, apenas escritas diferentemente:
```js run
-let str1 = "Hello\nWorld"; // two lines using a "newline symbol"
+let str1 = "Hello\nWorld"; // duas linhas usando um "caractere de nova linha"
-// two lines using a normal newline and backticks
+// duas linhas usando uma nova linha normalmente e crases
let str2 = `Hello
World`;
alert(str1 == str2); // true
```
-There are other, less common special characters:
+Existem outros, menos comuns, caracteres especiais:
-| Character | Description |
+| Caractere | Descrição |
|-----------|-------------|
-|`\n`|New line|
-|`\r`|In Windows text files a combination of two characters `\r\n` represents a new break, while on non-Windows OS it's just `\n`. That's for historical reasons, most Windows software also understands `\n`. |
-|`\'`, `\"`, \\`|Quotes|
-|`\\`|Backslash|
+|`\n`|Nova linha|
+|`\r`|Nos arquivos de texto do Windows uma combinação de dois caracteres `\r\n` representam uma nova quebra, enquanto em SOs não Windows é apenas `\n`. Isso se dá por razões históricas, a maioria dos programas no Windows também compreendem `\n`. |
+|`\'`, `\"`, \\`| Aspas |
+|`\\`|Barra invertida|
|`\t`|Tab|
-|`\b`, `\f`, `\v`| Backspace, Form Feed, Vertical Tab -- mentioned for completeness, coming from old times, not used nowadays (you can forget them right now). |
+|`\b`, `\f`, `\v`| Backspace, Quebra de página(Form Feed) e Barra vertical -- Mencionados para fins de completude, advindos de tempos antigos, não utilizadas atualmente (pode esquecê-los nesse momento) |
-As you can see, all special characters start with a backslash character `\`. It is also called an "escape character".
+Como você pode ver, todos os caracteres especiais começam com o caractere de barra invertida. Também chamado de "caractere de escape".
-Because it's so special, if we need to show an actual backslash `\` within the string, we need to double it:
+Por ser tão especial, se precisarmos mostrar uma barra invertida real `\` dentro da string, precisamos duplicá-la:
```js run
-alert( `The backslash: \\` ); // The backslash: \
+alert( `The backslash: \\` ); // A barra invertida: \
```
-So-called "escaped" quotes `\'`, `\"`, \\` are used to insert a quote into the same-quoted string.
+As chamadas aspas "escapadas" `\'`, `\"`, \\` são usadas para adicionar aspas do mesmo tipo da utilizada na delimitação da string.
-For instance:
+Por exemplo:
```js run
alert( 'I*!*\'*/!*m the Walrus!' ); // *!*I'm*/!* the Walrus!
```
-As you can see, we have to prepend the inner quote by the backslash `\'`, because otherwise it would indicate the string end.
+Como você pode ver, temos que adicionar a barra invertida `\'` antes da aspa interna, caso contrário ela indicaria o fim da string.
-Of course, only the quotes that are the same as the enclosing ones need to be escaped. So, as a more elegant solution, we could switch to double quotes or backticks instead:
+Claro, apenas as aspas do mesmo tipo utilizadas como delimitador precisam ser "escapadas". Então, como uma solução mais elegante, podemos trocar por aspas duplas ou crases
```js run
alert( "I'm the Walrus!" ); // I'm the Walrus!
```
-Besides these special characters, there's also a special notation for Unicode codes `\u…`, it's rarely used and is covered in the optional chapter about [Unicode](info:unicode).
+Apesar desses caracteres especiais, também há uma notação especial para códigos Unicode `\u…`, é raramente utilizada e é abordada no capítulo opcional sobre [Unicode](info:unicode).
-## String length
+## comprimento de string
-The `length` property has the string length:
+A propriedade `length` contém o tamanho da string:
```js run
alert( `My\n`.length ); // 3
```
-Note that `\n` is a single "special" character, so the length is indeed `3`.
+Note que `\n` é um único caractere "especial", então por isso o tamanho é na verdade `3`.
-```warn header="`length` is a property"
-People with a background in some other languages sometimes mistype by calling `str.length()` instead of just `str.length`. That doesn't work.
+```warn header="`length` é uma propriedade"
+Pessoas com alguma experiência em outras linguagens podem errar por chamar `str.length()` ao invés de apenas `str.length`. Isso não funciona.
-Please note that `str.length` is a numeric property, not a function. There is no need to add parenthesis after it. Not `.length()`, but `.length`.
+Veja, por favor, que `str.length` é uma propriedade numérica, não uma função. Não há necessidade de utilizar parênteses após a chamada. Não `.length()`, mas sim `.length`.
```
-## Accessing characters
+## Acessando Caracteres
-To get a character at position `pos`, use square brackets `[pos]` or call the method [str.at(pos)](mdn:js/String/at). The first character starts from the zero position:
+Para acessar um caractere na posição `pos`, use colchetes `[pos]` ou chame o método [str.at(pos)](mdn:js/String/at). O primeiro caractere se encontra na posição zero:
```js run
let str = `Hello`;
-// the first character
+// o primeiro caractere
alert( str[0] ); // H
alert( str.at(0) ); // H
-// the last character
+// o último caractere
alert( str[str.length - 1] ); // o
alert( str.at(-1) );
```
-As you can see, the `.at(pos)` method has a benefit of allowing negative position. If `pos` is negative, then it's counted from the end of the string.
+Como você pode ver, o método `.at(pos)` tem o benefício de permitir posições negativas. Se `pos` é negativo, então a contagem começará do fim da string.
-So `.at(-1)` means the last character, and `.at(-2)` is the one before it, etc.
+Assim `.at(-1)`remete ao último caractere, `.at(-2)` remete ao antepenúltimo, e assim por diante.
-The square brackets always return `undefined` for negative indexes, for instance:
+Os colchetes sempre retornam `undefined` para índices negativos, por exemplo:
```js run
let str = `Hello`;
@@ -156,80 +156,80 @@ alert( str[-2] ); // undefined
alert( str.at(-2) ); // l
```
-We can also iterate over characters using `for..of`:
+Também podemos iterar pelos caracteres usando `for..of`:
```js run
for (let char of "Hello") {
- alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc)
+ alert(char); // H,e,l,l,o (char vira "H", então "e", então "l" etc)
}
```
-## Strings are immutable
+## Strings são imutáveis
-Strings can't be changed in JavaScript. It is impossible to change a character.
+Strings não podem ser mudadas em JavaScript. É impossível mudar um caractere.
-Let's try it to show that it doesn't work:
+Vamos tentar isso para demonstrar que não funciona:
```js run
let str = 'Hi';
str[0] = 'h'; // error
-alert( str[0] ); // doesn't work
+alert( str[0] ); // não funciona
```
-The usual workaround is to create a whole new string and assign it to `str` instead of the old one.
+A maneira comum é criar toda uma nova string e atribuí-la a `str` ao invés da antiga.
-For instance:
+Por exemplo:
```js run
let str = 'Hi';
-str = 'h' + str[1]; // replace the string
+str = 'h' + str[1]; // substitui a string
alert( str ); // hi
```
-In the following sections we'll see more examples of this.
+Nas seções posteriores veremos mais exemplos disso.
-## Changing the case
+## Alterando entre maiúscula e minúscula
-Methods [toLowerCase()](mdn:js/String/toLowerCase) and [toUpperCase()](mdn:js/String/toUpperCase) change the case:
+Métodos [toLowerCase()](mdn:js/String/toLowerCase) e [toUpperCase()](mdn:js/String/toUpperCase) alteram a caixa do caractere:
```js run
alert( 'Interface'.toUpperCase() ); // INTERFACE
alert( 'Interface'.toLowerCase() ); // interface
```
-Or, if we want a single character lowercased:
+Ou, se quisermos que apenas uma letra fique minúscula:
```js run
alert( 'Interface'[0].toLowerCase() ); // 'i'
```
-## Searching for a substring
+## Procurando por uma substring
-There are multiple ways to look for a substring within a string.
+Existem muitas maneiras de procurar por uma substring dentro de uma string.
### str.indexOf
-The first method is [str.indexOf(substr, pos)](mdn:js/String/indexOf).
+O primeiro método é [str.indexOf(substr, pos)](mdn:js/String/indexOf).
-It looks for the `substr` in `str`, starting from the given position `pos`, and returns the position where the match was found or `-1` if nothing can be found.
+O método procura a `substr` na `str`, começando da posição dada em `pos`, e retorna a posição em que foi encontrada ou retorna `-1` se nada for encontrado.
-For instance:
+Por exemplo:
```js run
let str = 'Widget with id';
-alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning
-alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive
+alert( str.indexOf('Widget') ); // 0, porque 'Widget' encontra-se no começo
+alert( str.indexOf('widget') ); // -1, não encontrado, a procura é sensível à forma
-alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id)
+alert( str.indexOf("id") ); // 1, "id" encontra-se na posição 1 (..idget complementa o id)
```
-The optional second parameter allows us to start searching from a given position.
+O segundo parâmetro opcional permite-nos começar procurando da posição dada.
-For instance, the first occurrence of `"id"` is at position `1`. To look for the next occurrence, let's start the search from position `2`:
+Por exemplo, a primeira ocorrência de `"id"` é na posição `1`. Para encontrar a próxima ocorrência, vamos começar a procurar da posição `2`:
```js run
let str = 'Widget with id';
@@ -237,12 +237,12 @@ let str = 'Widget with id';
alert( str.indexOf('id', 2) ) // 12
```
-If we're interested in all occurrences, we can run `indexOf` in a loop. Every new call is made with the position after the previous match:
+Se estivermos interessados por todas as ocorrências, podemos chamar `indexOf` em um loop. Toda nova chamada é feita com a posição posterior ao último encontro:
```js run
let str = 'As sly as a fox, as strong as an ox';
-let target = 'as'; // let's look for it
+let target = 'as'; // Vamos procurar por isso
let pos = 0;
while (true) {
@@ -250,11 +250,11 @@ while (true) {
if (foundPos == -1) break;
alert( `Found at ${foundPos}` );
- pos = foundPos + 1; // continue the search from the next position
+ pos = foundPos + 1; // continue a procura a partir da próxima posição
}
```
-The same algorithm can be layed out shorter:
+O mesmo algoritmo pode ser organizado de maneira mais curta:
```js run
let str = "As sly as a fox, as strong as an ox";
@@ -269,40 +269,40 @@ while ((pos = str.indexOf(target, pos + 1)) != -1) {
```
```smart header="`str.lastIndexOf(substr, position)`"
-There is also a similar method [str.lastIndexOf(substr, position)](mdn:js/String/lastIndexOf) that searches from the end of a string to its beginning.
+Também há um método similar [str.lastIndexOf(substr, position)](mdn:js/String/lastIndexOf) que procura do fim da string ao seu começo.
-It would list the occurrences in the reverse order.
+Isso listaria as ocorrências na ordem inversa.
```
-There is a slight inconvenience with `indexOf` in the `if` test. We can't put it in the `if` like this:
+Existe um pequeno inconveniente com `indexOf` em uma condicional `if`. We can't put it in the `if`. Não podemos inserí-lo assim:
```js run
let str = "Widget with id";
if (str.indexOf("Widget")) {
- alert("We found it"); // doesn't work!
+ alert("We found it"); // Não funciona!
}
```
-The `alert` in the example above doesn't show because `str.indexOf("Widget")` returns `0` (meaning that it found the match at the starting position). Right, but `if` considers `0` to be `false`.
+o `alert` no exemplo acima não é mostrado porque `str.indexOf("Widget")` retorna `0` (significando que foi encontrado na posição de início). Certo, mas `if` considera `0` como `false`.
-So, we should actually check for `-1`, like this:
+Então, devemos checar através do `-1`, dessa forma:
```js run
-let str = "Widget with id";
+let str = "Widget com id";
*!*
if (str.indexOf("Widget") != -1) {
*/!*
- alert("We found it"); // works now!
+ alert("We found it"); // agora funciona!
}
```
### includes, startsWith, endsWith
-The more modern method [str.includes(substr, pos)](mdn:js/String/includes) returns `true/false` depending on whether `str` contains `substr` within.
+O método mais moderno [str.includes(substr, pos)](mdn:js/String/includes) retorna `true/false` a depender se a `str` contém a `substr` dentro.
-It's the right choice if we need to test for the match, but don't need its position:
+É a escolha correta se precisamos checar para o encontro, mas não precisamos da sua posição:
```js run
alert( "Widget with id".includes("Widget") ); // true
@@ -314,147 +314,147 @@ The optional second argument of `str.includes` is the position to start searchin
```js run
alert( "Widget".includes("id") ); // true
-alert( "Widget".includes("id", 3) ); // false, from position 3 there is no "id"
+alert( "Widget".includes("id", 3) ); // false, a partir da posição 3 não há "id"
```
-The methods [str.startsWith](mdn:js/String/startsWith) and [str.endsWith](mdn:js/String/endsWith) do exactly what they say:
+Os métodos [str.startsWith](mdn:js/String/startsWith) e [str.endsWith](mdn:js/String/endsWith) fazem exatamente o que dizem.
```js run
-alert( "*!*Wid*/!*get".startsWith("Wid") ); // true, "Widget" starts with "Wid"
-alert( "Wid*!*get*/!*".endsWith("get") ); // true, "Widget" ends with "get"
+alert( "*!*Wid*/!*get".startsWith("Wid") ); // true, "Widget" começa com "Wid"
+alert( "Wid*!*get*/!*".endsWith("get") ); // true, "Widget" termina com "get"
```
-## Getting a substring
+## Obtendo uma string
-There are 3 methods in JavaScript to get a substring: `substring`, `substr` and `slice`.
+Existem 3 métodos em JavaScript para obter uma substring: `substring`, `substr` e `slice`.
`str.slice(start [, end])`
-: Returns the part of the string from `start` to (but not including) `end`.
+: Retorna a parte da string do começo `start` até (mas não incluindo) o `end`.
- For instance:
+ Por exemplo:
```js run
let str = "stringify";
- alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5)
- alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0
+ alert( str.slice(0, 5) ); // 'strin', a substring do 0 ao 5 (sem incluir o 5)
+ alert( str.slice(0, 1) ); // 's', do 0 ao 1, mas sem incluir o 1, então apenas o caractere do 0
```
- If there is no second argument, then `slice` goes till the end of the string:
+ Se não houver um segundo argumento, então slice irá até o final da string:
```js run
let str = "st*!*ringify*/!*";
- alert( str.slice(2) ); // 'ringify', from the 2nd position till the end
+ alert( str.slice(2) ); // 'ringify', da segunda posição até o final
```
- Negative values for `start/end` are also possible. They mean the position is counted from the string end:
+ Valores negativos para `start/end` também são possíveis. Valores assim significam que a posição será contada a partir do final da string:
```js run
let str = "strin*!*gif*/!*y";
- // start at the 4th position from the right, end at the 1st from the right
+ // start na quarta posição a partir da direita e end na primeira posição a partir da direita
alert( str.slice(-4, -1) ); // 'gif'
```
`str.substring(start [, end])`
-: Returns the part of the string *between* `start` and `end` (not including `end`).
+: Retorna a parte da *entre* `start` e `end` (não incluindo `end`).
- This is almost the same as `slice`, but it allows `start` to be greater than `end` (in this case it simply swaps `start` and `end` values).
+ Isso é quase a mesma coisa que `slice`, mas esse método permite que `start` seja maior que `end` (nesse caso os valores de `start` e `end` são simplesmente trocados um pelo outro).
- For instance:
+ Por exemplo:
```js run
let str = "st*!*ring*/!*ify";
- // these are same for substring
+ // estes são iguais para substring
alert( str.substring(2, 6) ); // "ring"
alert( str.substring(6, 2) ); // "ring"
- // ...but not for slice:
- alert( str.slice(2, 6) ); // "ring" (the same)
- alert( str.slice(6, 2) ); // "" (an empty string)
+ // ...mas não para slice:
+ alert( str.slice(2, 6) ); // "ring" (mesma coisa)
+ alert( str.slice(6, 2) ); // "" (uma string vazia)
```
- Negative arguments are (unlike slice) not supported, they are treated as `0`.
+ Argumentos negativos (a não ser em slice) não são suportados, sendo tratados como `0`.
`str.substr(start [, length])`
-: Returns the part of the string from `start`, with the given `length`.
+: Retorna a parte da string a partir do `start`, com o `length` (comprimento) fornecido.
- In contrast with the previous methods, this one allows us to specify the `length` instead of the ending position:
+ Ao contrário dos métodos anteriores, esse nos permite especificar o `length` no lugar da posição final:
```js run
let str = "st*!*ring*/!*ify";
- alert( str.substr(2, 4) ); // 'ring', from the 2nd position get 4 characters
+ alert( str.substr(2, 4) ); // 'ring', a partir da segunda posição com 4 caracteres
```
- The first argument may be negative, to count from the end:
+ O primeiro argumento pode ser negativo para contar a posição a partir do final:
```js run
let str = "strin*!*gi*/!*fy";
- alert( str.substr(-4, 2) ); // 'gi', from the 4th position get 2 characters
+ alert( str.substr(-4, 2) ); // 'gi', a partir da quarta posição inversa com 2 caracteres
```
- This method resides in the [Annex B](https://tc39.es/ecma262/#sec-string.prototype.substr) of the language specification. It means that only browser-hosted Javascript engines should support it, and it's not recommended to use it. In practice, it's supported everywhere.
+ Esse método reside no [Annex B](https://tc39.es/ecma262/#sec-string.prototype.substr) da especificação da linguagem. Isso significa que apenas engines de JavaScript hospedados em navegadores devem suportá-lo. Na prática, é suportado em todo lugar.
-Let's recap these methods to avoid any confusion:
+Vamos recapitular esses métodos para evitar qualquer confusão:
-| method | selects... | negatives |
+| método | seleciona... | negativos |
|--------|-----------|-----------|
-| `slice(start, end)` | from `start` to `end` (not including `end`) | allows negatives |
-| `substring(start, end)` | between `start` and `end` (not including `end`)| negative values mean `0` |
-| `substr(start, length)` | from `start` get `length` characters | allows negative `start` |
+| `slice(start, end)` | de `start` a `end` (sem incluir `end`) | permite negativos |
+| `substring(start, end)` | entre `start` e `end` (sem incluir `end`) | valores negativos recebem `0` |
+| `substr(start, length)` | de `start` com `length` caracteres | permite negativos em `start` |
-```smart header="Which one to choose?"
-All of them can do the job. Formally, `substr` has a minor drawback: it is described not in the core JavaScript specification, but in Annex B, which covers browser-only features that exist mainly for historical reasons. So, non-browser environments may fail to support it. But in practice it works everywhere.
+```smart header="Qual deles escolher?"
+Todos eles podem fazer o trabalho. Formalmente, `substr` tem uma pequena desvantagem: não está descrita na especificação principal do JavaScript, mas sim no Annex B, que cobre apenas funcionalidades do navegador principalmente por motivos históricos. Então, ambientes fora dos navegadores podem falhar no suporte a essa funcionalidade. Mas, na prática funciona em qualquer lugar.
-Of the other two variants, `slice` is a little bit more flexible, it allows negative arguments and shorter to write.
+Das outras duas variantes, `slice` é um pouco mais flexível, permitindo argumentos negativos e mais curto de escrever.
-So, for practical use it's enough to remember only `slice`.
+Então, para usos práticos é suficiente guardar apenas lembrar-se de `slice`.
```
-## Comparing strings
+## Comparando strings
-As we know from the chapter , strings are compared character-by-character in alphabetical order.
+Como vimos no capítulo , strings são comparadas caractere-por-caractere em ordem alfabética.
-Although, there are some oddities.
+Entretanto, existem algumas peculiaridades..
-1. A lowercase letter is always greater than the uppercase:
+1. Uma letra minúscula é sempre menor que uma maiúscula:
```js run
alert( 'a' > 'Z' ); // true
```
-2. Letters with diacritical marks are "out of order":
+2. Letras com sinais diacríticos são "quebrados":
```js run
alert( 'Österreich' > 'Zealand' ); // true
```
- This may lead to strange results if we sort these country names. Usually people would expect `Zealand` to come after `Österreich` in the list.
+ Isso talvez gere resultados estranhos se tentarmos ordenar esses nomes de países. Pessoas normalmente esperariam que `Zealand` viria depois de `Österreich` na lista.
-To understand what happens, we should be aware that strings in Javascript are encoded using [UTF-16](https://en.wikipedia.org/wiki/UTF-16). That is: each character has a corresponding numeric code.
+Para entender porque isso acontece, deveríamos ser avisados que strings em JavaScript são codificadas usando [UTF-16](https://en.wikipedia.org/wiki/UTF-16). Isso é: cada caractere tem um código numérico correspondente.
-There are special methods that allow to get the character for the code and back:
+Existem métodos especiais que nos permitem acessar o caractere pelo seu código e vice-versa:
`str.codePointAt(pos)`
-: Returns a decimal number representing the code for the character at position `pos`:
+: Retorna um número em sistema decimal representando o código para o caractere na posição `pos`:
```js run
- // different case letters have different codes
+ // letras maiúsculas e minúsculas têm códigos diferentes
alert( "Z".codePointAt(0) ); // 90
alert( "z".codePointAt(0) ); // 122
- alert( "z".codePointAt(0).toString(16) ); // 7a (if we need a hexadecimal value)
+ alert( "z".codePointAt(0).toString(16) ); // 7a (se precisarmos de um valor hexadecimal)
```
`String.fromCodePoint(code)`
-: Creates a character by its numeric `code`
+: Cria um caractere através do seu código (`code`) numérico.
```js run
alert( String.fromCodePoint(90) ); // Z
- alert( String.fromCodePoint(0x5a) ); // Z (we can also use a hex value as an argument)
+ alert( String.fromCodePoint(0x5a) ); // Z (podemos também usar um valor hexadecimal como argumento)
```
-Now let's see the characters with codes `65..220` (the latin alphabet and a little bit extra) by making a string of them:
+Agora vamos ver os caracteres com os códigos `65..220` (o alfabeto latino e um pouco mais) fazendo uma string como eles.
```js run
let str = '';
@@ -468,55 +468,55 @@ alert( str );
// ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜ
```
-See? Capital characters go first, then a few special ones, then lowercase characters, and `Ö` near the end of the output.
+Vê? Letras maiúsculas vão primeiro, então alguns caracteres especiais, então letras minúsculas e `Ö` perto do final do output
-Now it becomes obvious why `a > Z`.
+Agora fica óbvio porque `a > Z`.
-The characters are compared by their numeric code. The greater code means that the character is greater. The code for `a` (97) is greater than the code for `Z` (90).
+Os caracteres são comparados através do seu código numérico. Maior código significa caractere maior. O código para `a` (97) é maior que o código para `Z` (90).
-- All lowercase letters go after uppercase letters because their codes are greater.
-- Some letters like `Ö` stand apart from the main alphabet. Here, its code is greater than anything from `a` to `z`.
+- Todas as letras minúsculas vão depois das letras maiúsculas pois seus códigos são maiores.
+- Alguma letras como `Ö` residem aparte do alfabeto principal. Nesse sentido, seu código é maior que qualquer coisa do `a` ao `z`.
-### Correct comparisons [#correct-comparisons]
+### Comparações corretas [#correct-comparisons]
-The "right" algorithm to do string comparisons is more complex than it may seem, because alphabets are different for different languages.
+O algoritmo "certo" para fazer uma comparação de strings é mais complexo do que pode parecer, isso porque alfabetos são diferentes para idiomas diferentes.
-So, the browser needs to know the language to compare.
+Então, o navegador precisa saber o idioma para comparar.
-Luckily, modern browsers support the internationalization standard [ECMA-402](https://www.ecma-international.org/publications-and-standards/standards/ecma-402/).
+Felizmente, navegadores modernos suportam o padrão de internacionalização [ECMA-402](https://www.ecma-international.org/publications-and-standards/standards/ecma-402/).
-It provides a special method to compare strings in different languages, following their rules.
+Ela provém um método especial para comparar strings em idiomas diferentes, seguindo suas regras internas.
-The call [str.localeCompare(str2)](mdn:js/String/localeCompare) returns an integer indicating whether `str` is less, equal or greater than `str2` according to the language rules:
+A chamada [str.localeCompare(str2)](mdn:js/String/localeCompare) retorna um inteiro indicando se `str` é menor, igual ou maior que `str2` de acordo com as regras do idioma:
-- Returns a negative number if `str` is less than `str2`.
-- Returns a positive number if `str` is greater than `str2`.
-- Returns `0` if they are equivalent.
+- Retorna um número negativo se `str` é menor que `str2`.
+- Retorna um número positivo se `str` é maior que `str2`.
+- Retorna `0` se eles forem equivalentes.
-For instance:
+Por exemplo:
```js run
alert( 'Österreich'.localeCompare('Zealand') ); // -1
```
-This method actually has two additional arguments specified in [the documentation](mdn:js/String/localeCompare), which allows it to specify the language (by default taken from the environment, letter order depends on the language) and setup additional rules like case sensitivity or should `"a"` and `"á"` be treated as the same etc.
+Esse método na verdade tem dois argumentos adicionais especificados na [documentação](mdn:js/String/localeCompare), que permite especificar o idioma (por padrão sendo pego pelo ambiente, a ordem das letras depende do idioma) e pôr regras extras como sensibilidade à maiúsculo e minúsculo ou ter que tratar `"a"` e `"á"` como iguais, etc.
-## Summary
+## Resumo
-- There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions `${…}`.
-- We can use special characters, such as a line break `\n`.
-- To get a character, use: `[]` or `at` method.
-- To get a substring, use: `slice` or `substring`.
-- To lowercase/uppercase a string, use: `toLowerCase/toUpperCase`.
-- To look for a substring, use: `indexOf`, or `includes/startsWith/endsWith` for simple checks.
-- To compare strings according to the language, use: `localeCompare`, otherwise they are compared by character codes.
+- Existem três tipos de aspas. Crases permitem uma string ser colocada em múltiplas linhas e interpolar expressões `${…}`.
+- Nós podemos usar caracteres especiais, como quebra de linha `\n`.
+- Para acessar um caractere, use: método `[]` ou `at`.
+- Para acessar uma substring, use: `slice` ou `substring`.
+- Para alterar as strings entre minúsculas/maiúsculas, use: `toLowerCase/toUpperCase`.
+- Para procurar por uma substring, use: `indexOf`, ou `includes/startsWith/endsWith` para checagens simples.
+- Para comparar strings de acordo com o idioma, use: `localeCompare`, caso contrário serão comparadas usando seus códigos de caracteres.
-There are several other helpful methods in strings:
+Existem mais diversos métodos úteis em strings:
-- `str.trim()` -- removes ("trims") spaces from the beginning and end of the string.
-- `str.repeat(n)` -- repeats the string `n` times.
-- ...and more to be found in the [manual](mdn:js/String).
+- `str.trim()` -- remove ("aparas") espaços do começo e do fim da string.
+- `str.repeat(n)` -- repete a string `n` vezes.
+- ...e mais a ser visto no [manual](mdn:js/String).
-Strings also have methods for doing search/replace with regular expressions. But that's big topic, so it's explained in a separate tutorial section .
+Strings também têm métodos para fazer procura/substituição com expressões regulares (Regex). Mas isso é um assunto extenso, então está explicado numa seção separada de tutoriais .
-Also, as of now it's important to know that strings are based on Unicode encoding, and hence there're issues with comparisons. There's more about Unicode in the chapter .
+Também, é importante saber que as strings são baseadas na codificação Unicode e, por isso, existem problemas com comparações. Há mais sobre Unicode no capítulo .