You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 9-regular-expressions/17-regexp-methods/article.md
+75-75Lines changed: 75 additions & 75 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,30 +1,30 @@
1
-
# Methods of RegExp and String
1
+
# Metodi di RegExp e String
2
2
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.
4
4
5
5
## str.match(regexp)
6
6
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`.
8
8
9
-
It has 3 modes:
9
+
Ha 3 modalità:
10
10
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`):
alert( result[1] ); // Script (primo gruppo di acquisizione)
20
20
alert( result.length ); // 2
21
21
22
22
// 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)
25
25
```
26
26
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.
28
28
```js run
29
29
let str = "I love JavaScript";
30
30
@@ -34,9 +34,9 @@ It has 3 modes:
34
34
alert( result.length ); // 1
35
35
```
36
36
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`.
38
38
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.:
40
40
41
41
```js run
42
42
let str = "I love JavaScript";
@@ -47,7 +47,7 @@ It has 3 modes:
47
47
alert(result.length); // Error: Cannot read property 'length' of null
48
48
```
49
49
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:
51
51
52
52
```js
53
53
let result = str.match(regexp) || [];
@@ -57,27 +57,27 @@ It has 3 modes:
57
57
58
58
[recent browser="new"]
59
59
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`.
61
61
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.
63
63
64
-
There are 3 differences from `match`:
64
+
Ci sono3differenze rispetto a`match`:
65
65
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`.
69
69
70
-
Usage example:
70
+
Esempio di utilizzo:
71
71
72
72
```js run
73
73
let str = '<h1>Hello, world!</h1>';
74
74
let regexp = /<(.*?)>/g;
75
75
76
76
let matchAll = str.matchAll(regexp);
77
77
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
79
79
80
-
matchAll = Array.from(matchAll); // array now
80
+
matchAll = Array.from(matchAll); // ora è un array
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`.
90
90
91
91
## str.split(regexp|substr, limit)
92
92
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.
94
94
95
-
We can use `split`with strings, like this:
95
+
Possiamo usare `split` con le stringhe, nel seguente modo:
96
96
97
97
```js run
98
-
alert('12-34-56'.split('-')) // array of ['12', '34', '56']
98
+
alert('12-34-56'.split('-')) // array di ['12', '34', '56']
99
99
```
100
100
101
-
But we can split by a regular expression, the same way:
101
+
Possiamo anche dividere con un'espressione regolare, allo stesso modo:
102
102
103
103
```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']
105
105
```
106
106
107
107
## str.search(regexp)
108
108
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:
110
110
111
111
```js run
112
112
let str = "A drop of ink may make a million think";
113
113
114
-
alert( str.search( /ink/i ) ); // 10 (first match position)
114
+
alert( str.search( /ink/i ) ); // 10 (posizione della prima corrispondenza)
115
115
```
116
116
117
-
**The important limitation:`search`only finds the first match.**
117
+
**La limitazione importante:`search`trova solo la prima corrispondenza.**
118
118
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)`.
120
120
121
121
## str.replace(str|regexp, str|func)
122
122
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.
124
124
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:
126
126
127
127
```js run
128
-
// replace a dash by a colon
128
+
// sostituire un trattino con i due punti
129
129
alert('12-34-56'.replace("-", ":")) // 12:34-56
130
130
```
131
131
132
-
There's a pitfall though.
132
+
Tuttavia, vi è un'insidia.
133
133
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.**
135
135
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 `":"`.
137
137
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`:
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):
196
196
197
197
```js run
198
198
let str ="John Smith";
@@ -202,7 +202,7 @@ let result = str.replace(/(\w+) (\w+)/, (match, name, surname) => `${surname}, $
202
202
alert(result); // Smith, John
203
203
```
204
204
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:
206
206
207
207
```js run
208
208
let str ="John Smith";
@@ -212,7 +212,7 @@ let result = str.replace(/(\w+) (\w+)/, (...match) => `${match[2]}, ${match[1]}`
212
212
alert(result); // Smith, John
213
213
```
214
214
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:
216
216
217
217
```js run
218
218
let str ="John Smith";
@@ -226,34 +226,34 @@ let result = str.replace(/(?<name>\w+) (?<surname>\w+)/, (...match) => {
226
226
alert(result); // Smith, John
227
227
```
228
228
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.
230
230
231
231
## str.replaceAll(str|regexp, str|func)
232
232
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:
234
234
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`.
237
237
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.
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.
251
251
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.
253
253
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.
255
255
256
-
But if there's flag `pattern:g`, then:
256
+
Ma se c'è una flag `pattern:g`, allora:
257
257
- A call to `regexp.exec(str)` returns the first match and saves the position immediately after it in the property `regexp.lastIndex`.
258
258
- The next such call starts the search from position `regexp.lastIndex`, returns the next match and saves the position after it in `regexp.lastIndex`.
0 commit comments