JavaScript RegExp test()
Esempio
Cerca in una stringa il carattere "e":
let text = "The best things in life are free";
let pattern = /e/;
let result = pattern.test(text);
Definizione e utilizzo
Il metodo test() verifica una corrispondenza in una stringa.
Se trova una corrispondenza, restituisce true, altrimenti restituisce false.
Supporto browser
test()
è una funzione ECMAScript1 (ES1).
ES1 (JavaScript 1997) è completamente supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |
Sintassi
RegExpObject.test(string)
Valori dei parametri
Parameter | Description |
---|---|
string | Required. The string to be searched |
Valore di ritorno
Type | Description |
---|---|
Boolean | Returns true if it finds a match, otherwise false |
Altri esempi
Esempio
Esegui una ricerca globale e verifica "Hello" e "W3Schools" in una stringa:
// The string:
let text = "Hello world!";
// Look for "Hello"
let pattern1 = /Hello/g;
let result1 = patt.test(text);
// Look for "W3Schools"
let pattern2 = /W3Schools/g;
let result2 = pattern2.test(text);
Metodi di ricerca per espressioni regolari
In JavaScript, una ricerca di testo con espressioni regolari può essere eseguita con metodi diversi.
Con un modello come espressione regolare, questi sono i metodi più comuni:
Esempio | Descrizione |
---|---|
text.match( modello ) | Il metodo String match() |
testo.ricerca ( modello ) | Il metodo String search() |
modello .exec(testo) | Il metodo RexExp exec() |
modello .test(testo) | Il metodo RegExp test() |