In JavaScript, a Regular Expression (RegEx) is an object that describes a sequence of characters used for defining a search pattern.
Create a RegEx
Using a regular expression literal
The regular expression consists of a pattern enclosed between slashes /
.
Ex:
1 | cost regularExp = /abc/; |
/abc/
is a regular expression.
Using the RegExp()
constructor function
Ex:
1 | const reguarExp = new RegExp('abc'); |
Ex:
1 2 | const regex = new RegExp(/^a...s$/); console.log(regex.test('alias')); // true |
In the above example, the string alias
matches with the RegEx pattern /^a...s$/
. Here, the test()
method is used to check if the string matches the pattern.
Modifiers
Modifier | Description |
---|---|
i | Perform case-insensitive matching |
g | Perform a global match (find all) |
m | Perform multiline matching |
d | Perform start and end matching (New in ES2022) |
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const string = 'Hello hello hello'; // performing a replacement const result1 = string.replace(/hello/, 'world'); console.log(result1); // Hello world hello // performing global replacement const result2 = string.replace(/hello/g, 'world'); console.log(result2); // Hello world world // performing case-insensitive replacement const result3 = string.replace(/hello/i, 'world'); console.log(result3); // world hello hello // performing global case-insensitive replacement const result4 = string.replace(/hello/gi, 'world'); console.log(result4); // world world world |
Brackets
Brackets are used to find a range of characters:
Bracket | Description |
---|---|
[abc] | Find any character between the brackets |
[^abc] | Find any character NOT between the brackets |
[0-9] | Find any character between the brackets (any digit) |
[^0-9] | Find any character NOT between the brackets (any non-digit) |
(x|y) | Find any of the alternatives specified |
Metacharacters
Metacharacters are characters with a special meaning:
Character | Description |
---|---|
. | Find a single character, except newline or line terminator |
\w | Find a word character |
\W | Find a non-word character |
\d | Find a digit |
\D | Find a non-digit character |
\s | Find a whitespace character |
\S | Find a non-whitespace character |
\b | Find a match at the beginning/end of a word, beginning like this: \bHI, end like this: HI\b |
\B | Find a match, but not at the beginning/end of a word |
\0 | Find a NULL character |
\n | Find a new line character |
\f | Find a form feed character |
\r | Find a carriage return character |
\t | Find a tab character |
\v | Find a vertical tab character |
\xxx | Find the character specified by an octal number xxx |
\xdd | Find the character specified by a hexadecimal number dd |
\udddd | Find the Unicode character specified by a hexadecimal number dddd |
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | let str = 'Sally sells seashells by the seashore'; let re = /s(?=e)/gi; console.log(str.replace(re, 'x')); // Output: Sally xells xeashells by the xeashore let str = '2001: A Space Odyssey'; let re = /\W/gi; console.log(str.replace(re, 'x')); // Output: 2001xxAxSpacexOdyssey re = /\d/gi; console.log(str.replace(re, 'x')); // Output: xxxx: A Space Odyssey re = /\d\D/gi; console.log(str.replace(re, 'x')); // Output: 200x A Space Odyssey |
Quantifiers
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 |
n{X} | Matches any string that contains a sequence of X n‘s |
n{X,Y} | Matches any string that contains a sequence of X to Y n‘s |
n{X,} | Matches any string that contains a sequence of at least X n‘s |
n$ | Matches any string with n at the end of it |
^n | Matches any string with n at the beginning of it |
?=n | Matches any string that is followed by a specific string n |
?!n | Matches any string that is not followed by a specific string n |
RegExp Object Properties
Property | Description |
---|---|
constructor | Returns the function that created the RegExp object’s prototype |
global | Checks whether the “g” modifier is set |
ignoreCase | Checks whether the “i” modifier is set |
lastIndex | Specifies the index at which to start the next match |
multiline | Checks whether the “m” modifier is set |
source | Returns the text of the RegExp pattern |
RegExp Object Methods
Method | Description |
---|---|
compile() | Deprecated in version 1.5. Compiles a regular expression |
exec() | Tests for a match in a string. Returns the first match |
test() | Tests for a match in a string. Returns true or false |
toString() | Returns the string value of the regular expression |
match() | Deprecated in version 1.5. Returns an array containing all the matches. It returns null on a mismatch. |
matchAll() | Returns an iterator containing all of the matches. |
search() | Tests for a match in a string and returns the index of the match. It returns -1 if the search fails. |
replace() | Searches for a match in a string and replaces the matched substring with a replacement substring. |
split() | Break a string into an array of substrings. |
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | const string = 'Find me'; const pattern = /me/; // search if the pattern is in string variable const result1 = string.search(pattern); console.log(result1); // 5 // replace the character with another character const string1 = 'Find me'; string1.replace(pattern, 'found you'); // Find found you // splitting strings into array elements const regex1 = /[\s,]+/; const result2 = 'Hello world! '.split(regex1); console.log(result2); // ['Hello', 'world!', ''] // searching the phone number pattern const regex2 = /(\d{3})\D(\d{3})-(\d{4})/g; const result3 = regex2.exec('My phone number is: 555 123-4567.'); console.log(result3); // ["555 123-4567", "555", "123", "4567"] |
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // program to validate the phone number function validatePhone(num) { // regex pattern for phone number const re = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/g; // check if the phone number is valid let result = num.match(re); if (result) { console.log('The number is valid.'); } else { let num = prompt('Enter number in XXX-XXX-XXXX format:'); validatePhone(num); } } // take input let number = prompt('Enter a number XXX-XXX-XXXX'); validatePhone(number); |
Output:
1 2 3 | Enter a number XXX-XXX-XXXX: 2343223432 Enter number in XXX-XXX-XXXX format: 234-322-3432 The number is valid |
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // program to validate the email address function validateEmail(email) { // regex pattern for email const re = /\S+@\S+\.\S+/g; // check if the email is valid let result = re.test(email); if (result) { console.log('The email is valid.'); } else { let newEmail = prompt('Enter a valid email:'); validateEmail(newEmail); } } // take input let email = prompt('Enter an email: '); validateEmail(email); |
Output:
1 2 3 | Enter an email: hellohello Enter a valid email: learningJS@gmail.com The email is valid. |