Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion modules/20-arithmetics/60-infinity/es/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ Infinity - 4; // Infinity
Infinity * Infinity; // Infinity
```

Sin embargo, hay algunos ejemplos en los que el infinito es útil. Este tema se analiza en detalle en Hexlet.
Sin embargo, hay algunos casos en los que el infinito resulta necesario. Por ejemplo, para fijar un límite superior e inferior o, al contrario, para quitarlo.
83 changes: 79 additions & 4 deletions modules/31-advanced-strings/25-interpolation/es/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,84 @@
La concatenación funciona, pero los template literals son más claros.

Recordemos cómo funciona la concatenación. Para ello unimos las cadenas necesarias (o las variables con cadenas dentro) mediante el signo `+`:

```javascript
const firstName = 'Joffrey';
const greeting = 'Hello';

console.log(greeting + ', ' + firstName + '!');
// => Hello, Joffrey!
```

Pero en expresiones complejas cuesta ver de inmediato qué texto se obtendrá al final. Sobre todo si en la cadena hay espacios, comas o comillas: empiezan a estorbar la lectura. Incluso el ejemplo actual exige un pequeño esfuerzo para entender cuál será el resultado.

Check notice on line 12 in modules/31-advanced-strings/25-interpolation/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/25-interpolation/es/README.md#L12

It appears that a hyphen is missing in the noun “to-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3]) Suggestions: `to-do`, `to do` URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3 Category: GRAMMAR
Raw output
modules/31-advanced-strings/25-interpolation/es/README.md:12:90: It appears that a hyphen is missing in the noun “to-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3])
 Suggestions: `to-do`, `to do`
 URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens 
 Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3
 Category: GRAMMAR

Check notice on line 12 in modules/31-advanced-strings/25-interpolation/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/25-interpolation/es/README.md#L12

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/31-advanced-strings/25-interpolation/es/README.md:12:152: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

Por esa razón, en muchos lenguajes existe una operación llamada interpolación. La interpolación es una forma de insertar los valores de las variables directamente dentro de una cadena. En JavaScript, para eso se usan las **plantillas de cadena** (template literals). Se escriben entre comillas invertidas `` ` ``, y las variables se insertan con `${}`:

```javascript
const greeting = 'Hola';
const firstName = 'Ana';
const firstName = 'Joffrey';
const greeting = 'Hello';

console.log(`${greeting}, ${firstName}!`);
// => Hola, Ana!
// => Hello, Joffrey!
```

Las comillas invertidas indican que dentro de la cadena se pueden usar variables. Sus nombres se escriben en `${}`, y JavaScript sustituye automáticamente los valores necesarios.

```text
firstName = 'Joff'
greeting = 'Hello'

`${greeting}, ${firstName}!`
└───┬───┘ └────┬────┘
'Hello' 'Joff'
└──────┬────────┘
'Hello, Joff!'
```

Compara estos dos ejemplos uno al lado del otro:

```javascript
console.log(greeting + ', ' + firstName + '!');
console.log(`${greeting}, ${firstName}!`);
```

La segunda variante es más simple y más clara.

## Cómo funciona

Todo lo que está dentro de `${}` se evalúa como una expresión de JavaScript, y el resultado se inserta en la cadena. Por eso dentro se pueden usar no solo variables, sino cualquier expresión: aritmética, llamadas a funciones y así sucesivamente.

```javascript
const price = 100;
const count = 3;

console.log(`Total: ${price * count}`);
// => Total: 300
```

## Las comillas invertidas son la clave

Una plantilla de cadena se escribe **obligatoriamente** entre comillas invertidas `` ` ``. Las comillas simples o dobles no funcionan para la interpolación:

```javascript
console.log('${firstName}'); // mostrará literalmente: ${firstName}
console.log(`${firstName}`); // mostrará el valor de la variable
```

## Ejemplo

```javascript
const school = 'Hexlet';

const whatIsIt = `${school} - online courses`;
console.log(whatIsIt); // => Hexlet - online courses
```

Esa forma de escribir se lee con facilidad: los espacios, los guiones y los símbolos se ven de inmediato. La cadena se parece exactamente a como aparecerá en la salida. Eso hace que el código sea claro y cómodo de mantener.

## Por qué esto importa

La interpolación es preferible a la concatenación en casi todos los lenguajes de programación modernos. Ella:

- simplifica la estructura de las cadenas;
- mejora la legibilidad del código;
- reduce la cantidad de errores al trabajar con espacios y signos de puntuación.
91 changes: 88 additions & 3 deletions modules/31-advanced-strings/30-symbols/es/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,91 @@
Accede a caracteres individuales con notación de corchetes e índice base cero.
A veces hace falta obtener un solo carácter de una cadena. Por ejemplo, si el sitio conoce el nombre y el apellido del usuario y hay que mostrarlos en formato abreviado, del tipo `A. Ivanov`. Para eso se necesita tomar la primera letra del nombre.

En JavaScript, para acceder a los caracteres de una cadena se usa la indexación. La indexación significa que cada carácter de la cadena tiene su propio número, es decir, su índice. La indexación empieza en cero: el primer carácter tiene el índice `0`, el segundo el `1` y así sucesivamente. Imaginemos que tenemos una cadena:

Check notice on line 3 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L3

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `El Segundo` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US Category: CASING
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:3:251: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `El Segundo`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING

```javascript
const firstName = 'Alexander';
```

Para obtener la primera letra, indicamos su posición (el índice) entre corchetes:

```javascript
console.log(firstName[0]); // => A

Check notice on line 12 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L12

Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2]) Suggestions: `Los Indios` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2 Category: MULTITOKEN_SPELLING
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:12:28: Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2])
 Suggestions: `Los Indios`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2
 Category: MULTITOKEN_SPELLING
```

Los índices en JavaScript (y en muchos lenguajes) empiezan en cero:

```text
Carácter A l e x a n d e r

Check notice on line 18 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L18

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:18:9: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC
Índice 0 1 2 3 4 5 6 7 8
```

La longitud de la cadena `Alexander` es `9`, por eso el índice del último carácter es `8`, es decir, `9 - 1`. La longitud de una cadena se puede averiguar con la función `length()`:

```javascript
import { length } from 'hexlet-basics/string';

console.log(length(firstName)); // => 9
console.log(firstName[length(firstName) - 1]); // => r
```

La línea `import` al principio del archivo conecta la función didáctica `length()` de la biblioteca: hay que copiarla tal cual. Cómo están hechas las importaciones lo veremos en las lecciones sobre módulos.

Si cambia la longitud de la cadena, el último carácter también se desplaza y habrá que volver a calcular su índice.

## Salirse de los límites de la cadena

A diferencia de algunos lenguajes, en JavaScript acceder a un índice que no existe no provoca un error: se devuelve un valor especial, `undefined`. Es el «aquí no hay nada» del mundo de JavaScript; lo veremos en detalle en el módulo sobre tipos de datos.

Check notice on line 37 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L37

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:37:26: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

```javascript
console.log(firstName[9]); // => undefined
```

Por eso, en programación se acostumbra a comprobar la longitud de la cadena y acceder a sus caracteres solo cuando es seguro. Llegaremos a eso en lecciones futuras.

Check notice on line 43 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L43

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:43:101: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

## Extraer caracteres desde el final

En algunos lenguajes (por ejemplo, en Python) para acceder a los caracteres desde el final se usan índices negativos. En JavaScript los corchetes **no** entienden los índices negativos: `firstName[-1]` devolverá `undefined`. Por eso el índice de un carácter contado desde el final se calcula a través de la longitud de la cadena:

Check notice on line 47 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L47

Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1]) Suggestions: `Los Indios` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1 Category: MULTITOKEN_SPELLING
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:47:126: Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1])
 Suggestions: `Los Indios`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1
 Category: MULTITOKEN_SPELLING

```javascript
import { length } from 'hexlet-basics/string';

const word = 'Hexlet';

console.log(word[length(word) - 1]); // => t, el último carácter
console.log(word[length(word) - 2]); // => e, el penúltimo carácter
```

```text
Cadena: 'H' 'e' 'x' 'l' 'e' 't'
Índice: 0 1 2 3 4 5
```

Aquí `length(word)` es igual a `6`, por eso el último carácter tiene el índice `length(word) - 1`, es decir, `5`. Este enfoque funciona correctamente incluso si la cadena cambia de longitud.

El índice se puede guardar en una variable:

```javascript
const word = 'hola';
console.log(word[0]); // => h
const index = 0;
console.log(word[index]); // => H
```

Este enfoque es útil cuando el índice se calcula en algún lugar del código y después se usa para acceder al carácter necesario.

## Caracteres especiales

En la indexación se cuentan las letras normales, los signos y los caracteres especiales. Todos ocupan una posición en la cadena y tienen su índice, aunque «no se vean» en la pantalla.

Check notice on line 76 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L76

It appears that a hyphen is missing in the plural noun “to-dos”? (TO_DO_HYPHEN[4]) Suggestions: `To-dos` URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=4 Category: GRAMMAR
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:76:30: It appears that a hyphen is missing in the plural noun “to-dos”? (TO_DO_HYPHEN[4])
 Suggestions: `To-dos`
 URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens 
 Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=4
 Category: GRAMMAR

Check notice on line 76 in modules/31-advanced-strings/30-symbols/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/30-symbols/es/README.md#L76

Unpaired symbol: ‘'’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/31-advanced-strings/30-symbols/es/README.md:76:159: Unpaired symbol: ‘'’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

Por ejemplo, en la cadena `'\nyou'` el primer carácter es `\n` (el salto de línea), y en el índice `1` ya está la letra `y`. Por eso el acceso `magic[1]` devolverá precisamente `y`.

## Piensa: ¿qué mostrará este código?

```javascript
const magic = '\nyou';
console.log(magic[1]); // => ?
```

La salida será:

```text
y
```
8 changes: 7 additions & 1 deletion modules/31-advanced-strings/70-slices/es/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
Dada `url = 'https://hexlet.io'`, extrae e imprime el dominio sin el protocolo.
Dada la constante `url = 'https://hexlet.io'`. Extrae y muestra en pantalla el nombre de dominio sin el protocolo:

Check notice on line 1 in modules/31-advanced-strings/70-slices/es/EXERCISE.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/EXERCISE.md#L1

Unpaired symbol: ‘'’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/31-advanced-strings/70-slices/es/EXERCISE.md:1:25: Unpaired symbol: ‘'’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

```text
hexlet.io
```

Usa el método `slice()`.
112 changes: 108 additions & 4 deletions modules/31-advanced-strings/70-slices/es/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,111 @@
Usa `slice()` para extraer parte de una cadena.
Al trabajar con cadenas nos encontramos a menudo con una tarea: extraer una parte de la cadena. Por ejemplo, obtener el año de una fecha, el nombre de un nombre completo o los primeros caracteres de una dirección de correo electrónico. Para esos casos, JavaScript tiene una herramienta cómoda: el método `slice()`.

## ¿Qué es una subcadena?

Una subcadena es una parte de una cadena, algo que está contenido dentro de otra cadena. Por ejemplo, en la cadena `'12-08-2034'` una subcadena puede ser `'2034'`, `'12'` o incluso `'-'`. Todo depende de qué información necesitemos extraer.

Check notice on line 5 in modules/31-advanced-strings/70-slices/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/README.md#L5

It appears that a hyphen is missing in the noun “To-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3]) Suggestions: `To-do`, `To do` URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3 Category: GRAMMAR
Raw output
modules/31-advanced-strings/70-slices/es/README.md:5:181: It appears that a hyphen is missing in the noun “To-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3])
 Suggestions: `To-do`, `To do`
 URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens 
 Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3
 Category: GRAMMAR

Supongamos que tenemos una cadena con la fecha `'12-08-2034'`. Queremos obtener de ella solo el año, `'2034'`. En esta cadena cada carácter tiene un índice (una posición), empezando por cero:

```text
'1' '2' '-' '0' '8' '-' '2' '0' '3' '4'
0 1 2 3 4 5 6 7 8 9
```

El año empieza en el índice 6 y termina en el 9. Para extraerlo usamos `slice()`:

```javascript
const value = '12-08-2034';
const year = value.slice(6, 10);
console.log(year); // => 2034
```

La forma de escribir «valor, punto, nombre» es una llamada a un método; qué son los métodos lo veremos en la lección sobre objetos, por ahora basta con usar `.slice()` siguiendo el ejemplo.

Check notice on line 22 in modules/31-advanced-strings/70-slices/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/README.md#L22

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/31-advanced-strings/70-slices/es/README.md:22:43: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

La llamada `value.slice(6, 10)` toma los caracteres desde el índice 6 hasta el 9 inclusive. El formato:

```text
cadena.slice(inicio, fin)
```

El carácter cuyo índice se indica como «fin» no se incluye. Se puede entender como el número del carácter ante el cual hay que detenerse.

```javascript
const value = 'code-basics';

console.log(value.slice(5, 11)); // => basics (del índice 5 al 10)
console.log(value.slice(0, 7)); // => code-ba (del índice 0 al 6)
console.log(value.slice(2, 6)); // => de-b
```

## El corte devuelve una cadena

`slice()` siempre devuelve una cadena, incluso si dentro solo hay dígitos. Eso significa que el resultado se puede usar como una cadena normal: concatenarlo, mostrarlo, pasarlo a funciones y volver a cortarlo:

```javascript
const value = '01-12-9873';

const part = value.slice(3, 7); // => 12-9
console.log(part.slice(0, 2)); // => 12
```

Primero obtuvimos la subcadena `'12-9'`, y después hicimos de ella un nuevo corte, `'12'`.

## Corte hasta el final o desde el principio

Check notice on line 53 in modules/31-advanced-strings/70-slices/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/README.md#L53

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `El Segundo` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US Category: CASING
Raw output
modules/31-advanced-strings/70-slices/es/README.md:53:29: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `El Segundo`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING

Si no se indica el segundo argumento, `slice()` devolverá todo desde el índice inicial hasta el final de la cadena. Y `slice(0)` o `slice()` sin argumentos devolverá la cadena completa:

Check notice on line 55 in modules/31-advanced-strings/70-slices/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/README.md#L55

It appears that a hyphen is missing in the noun “to-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3]) Suggestions: `to-do`, `to do` URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3 Category: GRAMMAR
Raw output
modules/31-advanced-strings/70-slices/es/README.md:55:25: It appears that a hyphen is missing in the noun “to-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3])
 Suggestions: `to-do`, `to do`
 URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens 
 Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3
 Category: GRAMMAR

```javascript
const text = 'Hello, World!';
console.log(text.slice(7)); // => World!
console.log(text.slice(7, 12)); // => World
const value = 'Hexlet';

console.log(value.slice(3)); // => let // del carácter 3 al final
console.log(value.slice(0, 3)); // => Hex // del principio al carácter 3
console.log(value.slice()); // => Hexlet // la cadena completa
```

## Índices negativos

`slice()` también sabe contar desde el final de la cadena. Para eso se usan índices negativos: `-1` corresponde al último carácter, `-2` al penúltimo y así sucesivamente. Es cómodo cuando no se conoce de antemano la longitud de la cadena, pero hay que tomar la «cola» o la «parte media» respecto al final:

```javascript
const value = 'Hexlet';

console.log(value.slice(-1)); // => t // el último carácter
console.log(value.slice(3, -1)); // => le // del 3 al penúltimo
console.log(value.slice(-3)); // => let // los últimos tres caracteres
```

## Corte con variables

Los límites del corte no tienen que estar fijados con números. Se pueden usar variables:

```javascript
const start = 1;
const end = 5;

const value = 'Hexlet';
console.log(value.slice(start, end)); // => exle
```

Esto resulta especialmente útil cuando los límites se calculan durante la ejecución del programa.

## Lo que `slice()` no tiene

En algunos lenguajes (por ejemplo, en Python) el corte tiene un tercer parámetro, el paso, y con él se puede tomar cada segundo carácter o invertir la cadena. El método `slice()` no tiene paso. Ese tipo de tareas en JavaScript se resuelven con bucles y otras herramientas a las que volveremos más adelante.

Check notice on line 93 in modules/31-advanced-strings/70-slices/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/README.md#L93

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `El Paso` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US Category: CASING
Raw output
modules/31-advanced-strings/70-slices/es/README.md:93:23: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `El Paso`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING

Existe también un método parecido, `substring()`. Funciona casi como `slice()`, pero no entiende los índices negativos (los trata como `0`), por eso para extraer la «cola» de una cadena resulta más cómodo `slice()`.

Check notice on line 95 in modules/31-advanced-strings/70-slices/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/README.md#L95

Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1]) Suggestions: `Los Indios` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1 Category: MULTITOKEN_SPELLING
Raw output
modules/31-advanced-strings/70-slices/es/README.md:95:33: Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1])
 Suggestions: `Los Indios`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1
 Category: MULTITOKEN_SPELLING

## Chuleta rápida

```javascript
const value = 'Hexlet';

value.slice(); // Hexlet — la cadena completa
value.slice(0); // Hexlet
value.slice(5); // t
value.slice(0, 5); // Hexle
value.slice(-1); // t — el último carácter
value.slice(-3); // let — los últimos tres caracteres
value.slice(2, -1); // xle — del tercero al penúltimo

Check notice on line 108 in modules/31-advanced-strings/70-slices/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/31-advanced-strings/70-slices/es/README.md#L108

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/31-advanced-strings/70-slices/es/README.md:108:55: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC
```

No te preocupes si ahora no memorizas todas las combinaciones: empezarás a usarlas en la práctica muy pronto. Lo principal es entender la estructura básica `cadena.slice(inicio, fin)`.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
Crea una variable `email` con texto multilínea e imprímelo:
Crea una variable `email` con texto multilínea y muéstrala en pantalla:

```text
Dear customer!

Your order has been accepted.
Expected delivery: 3 business days.
```

Usa una plantilla de cadena (comillas invertidas).
Loading
Loading