Skip to content

ES6 - RegExp

A regular expression (often shortened to “regex” or “regexp”) is a sequence of characters that defines a search pattern. These patterns are used by string-searching algorithms for “find” or “find and replace” operations on strings, or for input validation.

In JavaScript, regular expressions are also objects, represented by the RegExp class. Both the String prototype and RegExp prototype define methods that utilize regular expressions for powerful pattern-matching and text manipulation.

There are two ways to create a RegExp object:

// 1. Using a regular expression literal (preferred when the pattern is constant):
const patternLiteral = /abc/i; // Matches 'abc', 'Abc', 'aBc', etc., case-insensitively.
// 2. Using the RegExp constructor (useful when the pattern is dynamic, e.g., from user input):
const dynamicPattern = 'hello';
const flags = 'g'; // Global match
const patternConstructor = new RegExp(dynamicPattern, flags); // Matches 'hello' globally.
// Note: When using the constructor with a string pattern, backslashes need to be escaped.
// For example, to match a literal backslash: new RegExp('\\') corresponds to /\/.

Flags modify the behavior of the regular expression search. They are appended after the closing slash in a literal or passed as the second argument to the RegExp constructor.

FlagNameDescription
gGlobal matchFinds all matches rather than stopping after the first match.
iIgnore caseMakes the match case-insensitive.
mMultilineTreats beginning (^) and end ($) characters as working over multiple lines (i.e., match the beginning or end of each line, delimited by \n or \r), not just the very beginning or end of the whole input string.
uUnicode (ES6)Treats the pattern as a sequence of Unicode code points. Enables features like matching astral symbols (e.g., emoji) correctly with . and using Unicode property escapes like \p{Script=Greek}.
ySticky (ES6)Matches only from the index indicated by the lastIndex property of this regular expression in the target string. Does not attempt to match from any later indexes.
sDotAll / Singleline (ES2018)Allows the dot (.) metacharacter to match newline characters (\n, \r, etc.). Without s, . matches any character except newlines.

Brackets are used to define a set of characters to match.

ExpressionDescription
[abc]Matches any one character: ‘a’, ‘b’, or ‘c’.
[^abc]Negated set: Matches any one character that is NOT ‘a’, ‘b’, or ‘c’.
[0-9]Range: Matches any digit from 0 through 9.
[a-z]Range: Matches any lowercase letter from ‘a’ through ‘z’.
[A-Z]Range: Matches any uppercase letter from ‘A’ through ‘Z’.
[a-zA-Z0-9_]Commonly used to match letters, numbers, or underscore. Equivalent to \w.

Quantifiers specify how many times a character, group, or character class must be present in the input for a match to be found.

QuantifierDescription
x*Matches ‘x’ zero or more times.
x+Matches ‘x’ one or more times.
x?Matches ‘x’ zero or one time (optional).
x{n}Matches ‘x’ exactly n times.
x{n,}Matches ‘x’ at least n times.
x{n,m}Matches ‘x’ at least n times but not more than m times.
*?, +?, ??, {n,}?, {n,m}?Lazy quantifiers: Match as few characters as possible (non-greedy), as opposed to the default greedy behavior which matches as many as possible.
AnchorDescription
^Matches the beginning of the string (or line, if m flag is used).
$Matches the end of the string (or line, if m flag is used).
\bWord boundary: Matches a position between a word character (\w) and a non-word character (\W) or start/end of string.
\BNon-word boundary.

Parentheses group parts of a regular expression and create capturing groups. The matched substring can be remembered and accessed later.

  • (pattern): Capturing group. Matches pattern and captures the match.
  • (?:pattern): Non-capturing group. Matches pattern but does not capture the match.
  • (?<name>pattern): Named capturing group (ES2018). Captures the match and assigns it to groups.name.

These characters have special meanings in regular expressions. To match them literally, they usually need to be escaped with a backslash (\).

CharacterDescription
.Matches any single character except newline (unless s flag is used).
\dMatches any digit. Equivalent to [0-9].
\DMatches any non-digit. Equivalent to [^0-9].
\wMatches any word character (alphanumeric + underscore). Equivalent to [A-Za-z0-9_].
\WMatches any non-word character. Equivalent to [^A-Za-z0-9_].
\sMatches any whitespace character (space, tab, newline, etc.).
\SMatches any non-whitespace character.
\tMatches a tab character.
\nMatches a newline character.
\rMatches a carriage return character.
\uxxxxMatches the Unicode character specified by the hexadecimal number xxxx.
\p{...}, \P{...}Unicode property escapes (requires u flag, e.g., \p{Script=Latn}).

The | (OR) operator allows matching one of several expressions. E.g., /cat|dog/ matches ‘cat’ or ‘dog’.

PropertyDescription
RegExp.prototype.flags (ES6)A string containing the flags of the RegExp object (e.g., “giu”).
RegExp.prototype.globalBoolean: Whether the g flag is set.
RegExp.prototype.ignoreCaseBoolean: Whether the i flag is set.
RegExp.prototype.multilineBoolean: Whether the m flag is set.
RegExp.prototype.unicode (ES6)Boolean: Whether the u flag is set.
RegExp.prototype.sticky (ES6)Boolean: Whether the y flag is set.
RegExp.prototype.dotAll (ES2018)Boolean: Whether the s flag is set.
RegExp.prototype.sourceThe text of the pattern (without flags).
RegExp.prototype.lastIndexAn integer property that specifies the index at which to start the next match. Used by exec() and test() with the g or y flag.
  • RegExp.prototype.test(str): Executes a search for a match between a regular expression and a specified string. Returns true if a match is found, false otherwise.
  • RegExp.prototype.exec(str): Executes a search for a match in a specified string. Returns an array of information about the match (or null if no match). If the global flag (g) is set, exec() updates lastIndex and can be called repeatedly to find all matches.
  • String.prototype.match(regexp): Retrieves the result of matching a string against a regular expression. If regexp has the g flag, it returns an array of all matches or null. Without g, it returns the same as regexp.exec(string).
  • String.prototype.matchAll(regexp) (ES2020): Returns an iterator of all results matching a string against a regular expression, including capturing groups. Requires the g flag on the regexp.
  • String.prototype.replace(regexp|substr, newSubstr|function): Returns a new string with some or all matches of a pattern replaced by a replacement. The regexp can be a string or a RegExp object. The replacement can be a string (with special replacement patterns like $&, $1) or a function.
  • String.prototype.search(regexp): Executes a search for a match between a regular expression and this String object. Returns the index of the first match, or -1 if no match is found. Ignores the g flag.
  • String.prototype.split(separator|regexp[, limit]): Splits a String object into an array of strings by separating the string into substrings, using a specified separator string or regular expression.
const text = 'The quick brown fox jumps over the lazy dog. The dog barks.';
// Test if 'fox' exists (case-insensitive)
const hasFox = /fox/i.test(text);
console.log('Has fox?', hasFox); // true
// Execute and find first 'The'
const firstTheRegex = /The/;
const firstTheMatch = firstTheRegex.exec(text);
console.log('First \'The\' match:', firstTheMatch);
// Output: [ 'The', index: 0, input: '...', groups: undefined ]
// Find all occurrences of 'The' or 'the'
const allTheRegex = /the/gi;
let match;
const allMatches = [];
while ((match = allTheRegex.exec(text)) !== null) {
allMatches.push(match[0] + ' at index ' + match.index);
}
console.log('All \'the\' (global, case-insensitive):', allMatches);
// Output: [ 'The at index 0', 'the at index 31', 'The at index 44', 'the at index 48' ]
// Using String.match()
const animals = text.match(/fox|dog/g); // Global search for 'fox' or 'dog'
console.log('Animals found:', animals); // [ 'fox', 'dog', 'dog' ]
// Using String.replace()
const newText = text.replace(/dog/g, 'cat');
console.log('Replaced text:', newText);
// Output: The quick brown fox jumps over the lazy cat. The cat barks.
// Using String.split()
const sentences = 'Hello. How are you? Fine, thanks.';
const parts = sentences.split(/[.?]/); // Split by period or question mark
console.log('Split parts:', parts.filter(s => s.trim() !== '')); // Filter out empty strings from trailing delimiters
// Output: [ 'Hello', ' How are you', ' Fine, thanks' ]

Regular expressions are a powerful tool for text processing. Mastering them can significantly simplify many programming tasks. Online regex testers and resources like MDN Web Docs are invaluable for learning and experimenting.