June
28th,
2017
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
/pattern/modifiers;
var patt = /w3schools/i;Regular Expression Modifiers
| 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
| 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 |
| 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 |
| 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 |
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
var patt = /e/;
patt.test("The best things in life are free!"); // Since there is an "e" in the string, it returns trueThe exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text.
/e/.exec("The best things in life are free!"); // Since there is an "e" in the string, it returns e