Skip to content

Commit 472a5f0

Browse files
authored
Traduzione parziale
Traduzione parziale
1 parent 3c23af5 commit 472a5f0

1 file changed

Lines changed: 75 additions & 75 deletions

File tree

9-regular-expressions/17-regexp-methods/article.md

Lines changed: 75 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
1-
# Methods of RegExp and String
1+
# Metodi di RegExp e String
22

3-
In this article we'll cover various methods that work with regexps in-depth.
3+
In questo articolo analizzeremo estensivamente diversi metodi che funzionano con le espressioni regolari.
44

55
## str.match(regexp)
66

7-
The method `str.match(regexp)` finds matches for `regexp` in the string `str`.
7+
Il metodo `str.match(regexp)` trova corrispondenze di `regexp` all'interno della stringa `str`.
88

9-
It has 3 modes:
9+
Ha 3 modalità:
1010

11-
1. If the `regexp` doesn't have flag `pattern:g`, then it returns the first match as an array with capturing groups and properties `index` (position of the match), `input` (input string, equals `str`):
11+
1. Se la `regexp` non presenta la flag `pattern:g`, essa restituisce la prima corrispondenza sotto forma di array con i gruppi di acquisizione e le proprietà `index` (posizione della corrispondenza) e `input` (la stringa sorgente, ovvero `str`):
1212

1313
```js run
1414
let str = "I love JavaScript";
1515

1616
let result = str.match(/Java(Script)/);
1717

18-
alert( result[0] ); // JavaScript (full match)
19-
alert( result[1] ); // Script (first capturing group)
18+
alert( result[0] ); // JavaScript (corrispondenza completa)
19+
alert( result[1] ); // Script (primo gruppo di acquisizione)
2020
alert( result.length ); // 2
2121

2222
// Additional information:
23-
alert( result.index ); // 7 (match position)
24-
alert( result.input ); // I love JavaScript (source string)
23+
alert( result.index ); // 7 (posizione della corrispondenza)
24+
alert( result.input ); // I love JavaScript (stringa sorgente)
2525
```
2626

27-
2. If the `regexp` has flag `pattern:g`, then it returns an array of all matches as strings, without capturing groups and other details.
27+
2. Se la `regexp` presenta la flag `pattern:g`, restituisce un array contenente tutte le corrispondenze sotto forma di stringhe, senza i gruppi di acquisizione né ulteriori dettagli.
2828
```js run
2929
let str = "I love JavaScript";
3030
@@ -34,9 +34,9 @@ It has 3 modes:
3434
alert( result.length ); // 1
3535
```
3636

37-
3. If there are no matches, no matter if there's flag `pattern:g` or not, `null` is returned.
37+
3. Se non esistono corrispondenze, indipendentemente dalla presenza o meno della flag `pattern:g`, è restituito `null`.
3838

39-
That's an important nuance. If there are no matches, we don't get an empty array, but `null`. It's easy to make a mistake forgetting about it, e.g.:
39+
È una differenza sottile, ma importante. Se non esistono corrispondenze, infatti, non ci viene restituito un array vuoto, ma `null`. È facile sbagliare dimenticandosene, e.g.:
4040

4141
```js run
4242
let str = "I love JavaScript";
@@ -47,7 +47,7 @@ It has 3 modes:
4747
alert(result.length); // Error: Cannot read property 'length' of null
4848
```
4949

50-
If we want the result to be an array, we can write like this:
50+
Tuttavia, se desideriamo che il risultato sia un array, possiamo scrivere quanto segue:
5151

5252
```js
5353
let result = str.match(regexp) || [];
@@ -57,27 +57,27 @@ It has 3 modes:
5757

5858
[recent browser="new"]
5959

60-
The method `str.matchAll(regexp)` is a "newer, improved" variant of `str.match`.
60+
Il metodo `str.matchAll(regexp)` è una variante innovativa di `str.match`.
6161

62-
It's used mainly to search for all matches with all groups.
62+
È usato prevalentemente per cercare tutte le corrispondenze con tutti i gruppi di acquisizione.
6363

64-
There are 3 differences from `match`:
64+
Ci sono 3 differenze rispetto a `match`:
6565

66-
1. It returns an iterable object with matches instead of an array. We can make a regular array from it using `Array.from`.
67-
2. Every match is returned as an array with capturing groups (the same format as `str.match` without flag `pattern:g`).
68-
3. If there are no results, it returns an empty iterable object instead of `null`.
66+
1. Restituisce, al posto di un array, un oggetto iterabile contenente le corrispondenze. Da esso possiamo creare un array normale usando `Array.from`.
67+
2. Ogni corrispondenza è restituita sotto forma di un array con i gruppi di acquisizione (lo stesso formato di `str.match` senza la flag `pattern:g`).
68+
3. Se non esistono risultati, restituisce un oggetto iterabile vuoto al posto di `null`.
6969

70-
Usage example:
70+
Esempio di utilizzo:
7171

7272
```js run
7373
let str = '<h1>Hello, world!</h1>';
7474
let regexp = /<(.*?)>/g;
7575
7676
let matchAll = str.matchAll(regexp);
7777
78-
alert(matchAll); // [object RegExp String Iterator], not array, but an iterable
78+
alert(matchAll); // [object RegExp String Iterator], non un array, ma un oggetto iterabile
7979
80-
matchAll = Array.from(matchAll); // array now
80+
matchAll = Array.from(matchAll); // ora è un array
8181
8282
let firstMatch = matchAll[0];
8383
alert( firstMatch[0] ); // <h1>
@@ -86,97 +86,97 @@ alert( firstMatch.index ); // 0
8686
alert( firstMatch.input ); // <h1>Hello, world!</h1>
8787
```
8888

89-
If we use `for..of` to loop over `matchAll` matches, then we don't need `Array.from` any more.
89+
Se usiamo `for..of` to loop over le corrispondenze di `matchAll`, non necessitiamo più di `Array.from`.
9090

9191
## str.split(regexp|substr, limit)
9292

93-
Splits the string using the regexp (or a substring) as a delimiter.
93+
Divide la stringa usando l'espressione regolare (o una sottostringa) come separatore.
9494
95-
We can use `split` with strings, like this:
95+
Possiamo usare `split` con le stringhe, nel seguente modo:
9696
9797
```js run
98-
alert('12-34-56'.split('-')) // array of ['12', '34', '56']
98+
alert('12-34-56'.split('-')) // array di ['12', '34', '56']
9999
```
100100
101-
But we can split by a regular expression, the same way:
101+
Possiamo anche dividere con un'espressione regolare, allo stesso modo:
102102

103103
```js run
104-
alert('12, 34, 56'.split(/,\s*/)) // array of ['12', '34', '56']
104+
alert('12, 34, 56'.split(/,\s*/)) // array di ['12', '34', '56']
105105
```
106106

107107
## str.search(regexp)
108108

109-
The method `str.search(regexp)` returns the position of the first match or `-1` if none found:
109+
Il metodo `str.search(regexp)` restituisce la posizione della prima corrispondenza, o `-1` se non ne viene trovata alcuna:
110110

111111
```js run
112112
let str = "A drop of ink may make a million think";
113113
114-
alert( str.search( /ink/i ) ); // 10 (first match position)
114+
alert( str.search( /ink/i ) ); // 10 (posizione della prima corrispondenza)
115115
```
116116

117-
**The important limitation: `search` only finds the first match.**
117+
**La limitazione importante: `search` trova solo la prima corrispondenza.**
118118

119-
If we need positions of further matches, we should use other means, such as finding them all with `str.matchAll(regexp)`.
119+
Se abbiamo bisogno della posizione di una corrispondenza successiva, dobbiamo usare altri mezzi, ad esempio trovandole tutte con `str.matchAll(regexp)`.
120120

121121
## str.replace(str|regexp, str|func)
122122

123-
This is a generic method for searching and replacing, one of most useful ones. The swiss army knife for searching and replacing.
123+
Questo è un metodo generico per cercare e sostituire e uno dei più utili: è l'equivalente di un coltellino svizzero in questo campo.
124124
125-
We can use it without regexps, to search and replace a substring:
125+
Possiamo usarlo senza espressioni regolari, per cercare e sostituire una sottostringa:
126126
127127
```js run
128-
// replace a dash by a colon
128+
// sostituire un trattino con i due punti
129129
alert('12-34-56'.replace("-", ":")) // 12:34-56
130130
```
131131
132-
There's a pitfall though.
132+
Tuttavia, vi è un'insidia.
133133

134-
**When the first argument of `replace` is a string, it only replaces the first match.**
134+
**Quando il primo argomento di `replace` è una stringa, solo la prima corrispondenza viene sostituita.**
135135

136-
You can see that in the example above: only the first `"-"` is replaced by `":"`.
136+
Si può vedere nell'esempio sopra: solo il primo `"-"` è stato sostituito da `":"`.
137137
138-
To find all hyphens, we need to use not the string `"-"`, but a regexp `pattern:/-/g`, with the obligatory `pattern:g` flag:
138+
Per trovare tutti i trattini, non dobbiamo usare la stringa `"-"`, ma l'espressione regolare `pattern:/-/g`, obbligatoriamente con la flag`pattern:g`:
139139

140140
```js run
141-
// replace all dashes by a colon
141+
// sostituire tutti i trattini con i due punti
142142
alert( '12-34-56'.replace( *!*/-/g*/!*, ":" ) ) // 12:34:56
143143
```
144144

145-
The second argument is a replacement string. We can use special characters in it:
145+
Il secondo argomento è una stringa di sostituzione. Possiamo usare caratteri speciali al suo interno:
146146

147-
| Symbols | Action in the replacement string |
147+
| Simboli | Azione nella stringa di sostituzione |
148148
|--------|--------|
149-
|`$&`|inserts the whole match|
150-
|<code>$&#096;</code>|inserts a part of the string before the match|
151-
|`$'`|inserts a part of the string after the match|
152-
|`$n`|if `n` is a 1-2 digit number, inserts the contents of n-th capturing group, for details see [](info:regexp-groups)|
153-
|`$<name>`|inserts the contents of the parentheses with the given `name`, for details see [](info:regexp-groups)|
154-
|`$$`|inserts character `$` |
149+
|`$&`|inserisce l'intera corrispondenza|
150+
|<code>$&#096;</code>|inserisce una parte della stringa prima della corrispondenza|
151+
|`$'`|inserisce una parte della stringa dopo la corrispondenza|
152+
|`$n`|se `n` è un numero a una o 2 cifre, inserisce il contenuto dell'n-esimo gruppo di acquisizione, per i dettagli consultare [](info:regexp-groups)|
153+
|`$<name>`|inserisce il contenuto delle parentesi con il `name` fornito, per i dettagli consultare [](info:regexp-groups)|
154+
|`$$`|inserisce il carattere `$` |
155155
156-
For instance:
156+
Per esempio:
157157
158158
```js run
159159
let str = "John Smith";
160160

161-
// swap first and last name
161+
// inver
162162
alert(str.replace(/(john) (smith)/i, '$2, $1')) // Smith, John
163163
```
164164

165-
**For situations that require "smart" replacements, the second argument can be a function.**
165+
**Per situazioni che richiedono sostituzioni "intelligenti", il secondo argomento può essere una funzione.**
166166

167-
It will be called for each match, and the returned value will be inserted as a replacement.
167+
Essa sarà chiamata per ogni corrispondenza, e il valore restituito sarà inserito come sostituto.
168168

169-
The function is called with arguments `func(match, p1, p2, ..., pn, offset, input, groups)`:
169+
La funzione è chiamata con gli argomenti `func(match, p1, p2, ..., pn, offset, input, groups)`:
170170

171-
1. `match` -- the match,
172-
2. `p1, p2, ..., pn` -- contents of capturing groups (if there are any),
173-
3. `offset` -- position of the match,
174-
4. `input` -- the source string,
175-
5. `groups` -- an object with named groups.
171+
1. `match` -- la corrispondenza,
172+
2. `p1, p2, ..., pn` -- contenuti dei gruppi di acquisizione (se ce ne sono),
173+
3. `offset` -- posizione della corrispondenza,
174+
4. `input` -- la stringa sorgente,
175+
5. `groups` -- un oggetto con i gruppi nominati.
176176

177-
If there are no parentheses in the regexp, then there are only 3 arguments: `func(str, offset, input)`.
177+
Se non ci sono parentesi all'interno dell'espressione regolare, la funzione avrà solo 3 argomenti: `func(str, offset, input)`.
178178

179-
For example, let's uppercase all matches:
179+
Per esempio, rendiamo maiuscole tutte le corrispondenze:
180180

181181
```js run
182182
let str = "html and css";
@@ -186,13 +186,13 @@ let result = str.replace(/html|css/gi, str => str.toUpperCase());
186186
alert(result); // HTML and CSS
187187
```
188188

189-
Replace each match by its position in the string:
189+
Rimpiazzare ogni corrispondenza con la sua posizione nella stringa:
190190

191191
```js run
192192
alert("Ho-Ho-ho".replace(/ho/gi, (match, offset) => offset)); // 0-3-6
193193
```
194194

195-
In the example below there are two parentheses, so the replacement function is called with 5 arguments: the first is the full match, then 2 parentheses, and after it (not used in the example) the match position and the source string:
195+
Nell'esempio seguente ci sono due parentesi, pertanto la funzione di sostituzione è chiamata con 5 argomenti: la prima è la corrispondenza completa, poi le 2 parentesi, e dopo di esse la posizione della corrispondenza e la stringa sorgente (non usate nell'esempio):
196196

197197
```js run
198198
let str = "John Smith";
@@ -202,7 +202,7 @@ let result = str.replace(/(\w+) (\w+)/, (match, name, surname) => `${surname}, $
202202
alert(result); // Smith, John
203203
```
204204

205-
If there are many groups, it's convenient to use rest parameters to access them:
205+
Se sono presenti numerosi gruppi, è conveniente usare i parametri rest per accedervi:
206206

207207
```js run
208208
let str = "John Smith";
@@ -212,7 +212,7 @@ let result = str.replace(/(\w+) (\w+)/, (...match) => `${match[2]}, ${match[1]}`
212212
alert(result); // Smith, John
213213
```
214214

215-
Or, if we're using named groups, then `groups` object with them is always the last, so we can obtain it like this:
215+
O, se stiamo usando gruppi nominati, l'oggetto `groups` essi contenente è sempre l'ultimo, così possiamo ottenerlo in questo modo:
216216

217217
```js run
218218
let str = "John Smith";
@@ -226,34 +226,34 @@ let result = str.replace(/(?<name>\w+) (?<surname>\w+)/, (...match) => {
226226
alert(result); // Smith, John
227227
```
228228

229-
Using a function gives us the ultimate replacement power, because it gets all the information about the match, has access to outer variables and can do everything.
229+
Usare una funzione ci permette di usare un potere sostitutivo supremo, poiché ottiene tutte le informazioni sulla corrispondenza, ha accesso alle variabili esterne e può fare qualsiasi cosa.
230230

231231
## str.replaceAll(str|regexp, str|func)
232232

233-
This method is essentially the same as `str.replace`, with two major differences:
233+
Questo metodo è praticamente uguale a `str.replace`, ma con due differenze rilevanti:
234234

235-
1. If the first argument is a string, it replaces *all occurences* of the string, while `replace` replaces only the *first occurence*.
236-
2. If the first argument is a regular expression without the `g` flag, there'll be an error. With `g` flag, it works the same as `replace`.
235+
1. Se il primo argomento è una stringa, sostituisce *tutte le corrispondenze* della stringa, mentre `replace` sostituisce solamente la *prima corrispondenza*.
236+
2. Se il primo argomento è un'espressione regolare con la flag `g`, sarà generato un errore. Con la `g` flag, funziona come `replace`.
237237

238-
The main use case for `replaceAll` is replacing all occurences of a string.
238+
Il caso principale in cui si usa `replaceAll` è la sostituzione di tutte le corrispondenze di una stringa.
239239

240-
Like this:
240+
In questo modo:
241241

242242
```js run
243-
// replace all dashes by a colon
243+
// sostituire tutti i trattini con i due punti
244244
alert('12-34-56'.replaceAll("-", ":")) // 12:34:56
245245
```
246246

247247

248248
## regexp.exec(str)
249249

250-
The `regexp.exec(str)` method returns a match for `regexp` in the string `str`. Unlike previous methods, it's called on a regexp, not on a string.
250+
Il metodo `regexp.exec(str)` restituisce una corrispondenza di `regexp` nella stringa `str`. A differenza dei metodi precedenti, viene chiamato su un'espressione regolare, non su una stringa.
251251

252-
It behaves differently depending on whether the regexp has flag `pattern:g`.
252+
Si comporta differentemente a seconda della presenza o meno della flag `pattern:g` nell'espressione regolare.
253253

254-
If there's no `pattern:g`, then `regexp.exec(str)` returns the first match exactly as `str.match(regexp)`. This behavior doesn't bring anything new.
254+
Se non c'è `pattern:g`, `regexp.exec(str)` restituisce la prima corrispondenza, esattamente come `str.match(regexp)`. Questo comportamento non comporta niente di nuovo.
255255

256-
But if there's flag `pattern:g`, then:
256+
Ma se c'è una flag `pattern:g`, allora:
257257
- A call to `regexp.exec(str)` returns the first match and saves the position immediately after it in the property `regexp.lastIndex`.
258258
- The next such call starts the search from position `regexp.lastIndex`, returns the next match and saves the position after it in `regexp.lastIndex`.
259259
- ...And so on.

0 commit comments

Comments
 (0)