-
JAVASCRIPT > les expressions régulières (regex)
SYNTAXE
/RegEx/flags;REMPLACER
remplace la première occurrence trouvée :
chaine.replace( new RegExp(‘to‘,‘i’), ‘ta‘ );ou
chaine.replace( /to/i, ‘ta‘ );TESTER
var test = /to/.test(chaine);renvoie true si l’occurence est trouvée, sinon renvoie false.
CHERCHER
var chaine = "Voici une phrase : toto";var test = chaine.search(/to/i);renvoie -1 si rien n’est trouvé, sinon, renvoie la position de la première occurrence trouvée (0 étant la première position).
RETOURNER
var test = /to/.exec("Une phrase avec toto");Si une occurrence est trouvée, renvoie le résultat de la première occurrence trouvée, sinon renvoie null.
exemples :
var test = /to./.exec("to1 to2 to3″);→ to1var test = /ti./.exec("t01 to2 to3");→ nullPour chercher la dernière occurrence :
bar(?!.*bar)
bar # Match bar
(?! # but only if it's not followed by...
.* # zero or more characters
bar # literal bar
) # end of lookahead
If your string may contain newline characters, use
bar(?![\s\S]*bar)
instead.
[\s\S]
matches any character, including newlines.For example:
match = subject.match(/bar(?![\s\S]*bar)/); if (match != null) { // matched text: match[0] // match start: match.index }
You might also want to surround your search words (if they are indeed words composed of alphanumeric characters) with
\b
anchors to avoid partial matches.\bbar\b(?![\s\S]*\bbar\b)
matches the solitary
bar
instead of thebar
withinfoobar
:Don't match bar, do match bar, but not foobar! no match---^ match---^ no match---^
LES FLAGS
iPermet une application non sensible à la cassereplace( /to/i, ‘TO’ );gPermet une application globalereplace( /to/g, ‘ta’ );
mPermet une application multilignereplace( /to/m, ‘ta’ );LES ENCADREMENTS ( ) ET [ ]
[abc]Un des caractères présents entre les crochets
[0-9]Un des caractères compris entre 0 et 9
(x|y)Un des schéma compris entre parenthèse et séparés par |\d (digital)
\dTrouver une nombre\b (mot)
\bFind a match at the beginning or at the end of a wordQuantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n\s et \S (espaces)
\sTout caractère espacé ( espace - tabulation\t- retour charriot\r- saut de ligne\n- tabulation verticale ).\STout caractère non espacé ( espace - tabulation\t- retour charriot\r- saut de ligne\n- tabulation verticale ).VAR = "Ceci est une phrase"; var patt1 = /\S/g;
Quelques RegEx
REMPLACER LES SAUTS DE LIGNES PAR DES <BR> :
replace( new RegExp(‘\r?\n’,'g’), ‘<br>’ );
Using String Methods
In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a Regular Expression
Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
"highELE">var str = "highVAL">"Visit W3Schools";
"highELE">var n = str.search(/w3schools/i);The result in n will be:
6
Using String search() With String
The search method will also accept a string as search argument. The string argument will be converted to a regular expression:
Example
Use a string to do a search for "W3schools" in a string:
"highELE">var str = "highVAL">"Visit W3Schools!";
"highELE">var n = str.search("highVAL">"W3Schools");
Use String replace() With a Regular Expression
Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
"highELE">var str = "highVAL">"Visit Microsoft!";
"highELE">var res = str.replace(/microsoft/i, "highVAL">"W3Schools");The result in res will be:
Visit W3Schools!Using String replace() With a String
The replace() method will also accept a string as search argument:
"highELE">var str = "highVAL">"Visit Microsoft!";
"highELE">var res = str.replace("highVAL">"Microsoft", "highVAL">"W3Schools");
Did You Notice?
Regular expression arguments (instead of string arguments) can be used in the methods above.
Regular expressions can make your search much more powerful (case insensitive for example).
Regular Expression Modifiers
Modifiers can be used to perform case-insensitive more global searches:
Modifier Description i Perform case-insensitive matching g Perform a global match (find all matches rather than stopping after the first match) m Perform multiline matching Regular Expression Patterns
Brackets are used to find a range of characters:
Expression Description [abc] Find any of the characters between the brackets [0-9] Find any of the digits between the brackets (x|y) Find any of the alternatives separated with | Metacharacters are characters with a special meaning:
Metacharacter Description \d Find a digit \s Find a whitespace character \b Find a match at the beginning or at the end of a word \uxxxx Find the Unicode character specified by the hexadecimal number xxxx Quantifiers define quantities:
Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n
Using the RegExp Object
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
Using test()
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
The following example searches a string for the character "e":
Example
"highELE">var patt = /e/;
patt.test("highVAL">"The best things in life are free!");Since there is an "e" in the string, the output of the code above will be:
trueTry it yourself »You don’t have to put the regular expression in a variable first. The two lines above can be shortened to one:
/e/.test("highVAL">"The best things in life are free!");
Using exec()
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text.
If no match is found, it returns null.
The following example searches a string for the character "e":
Example 1
/e/.exec("highVAL">"The best things in life are free!");Since there is an "e" in the string, the output of the code above will be:
e
Complete RegExp Reference
For a complete reference, go to our Complete JavaScript RegExp Reference.
The reference contains descriptions and examples of all RegExp properties and methods.