Skip to content

JavaScript RegExp

A regular expression (RegExp) is an object that describes a sequence of characters used for pattern matching within strings. They are powerful tools for text search and replace operations.

A regular expression defines a search pattern. This pattern can be as simple as a single character or as complex as a sophisticated sequence defining specific structures in text.

Regular expressions are used to perform various text operations, including:

  • Searching for specific text patterns.
  • Replacing text that matches a pattern.
  • Validating input (e.g., email formats, passwords).
  • Extracting information from strings.

Regular expressions can be created in two ways:

1. Literal Notation: `/pattern/flags`
const regexLiteral = /w3schools/i;
2. Constructor: `new RegExp("pattern", "flags")`
const regexConstructor = new RegExp("w3schools", "i");

Example explained (/w3schools/i):

  • w3schools is the pattern to search for.
  • i is a flag (modifier) that makes the search case-insensitive.

Literal notation is generally preferred for performance when the pattern is constant.

Using String Methods with Regular Expressions

Section titled “Using String Methods with Regular Expressions”

JavaScript’s String object has several methods that work with regular expressions:

  • search(regexp): Searches for a match and returns the index of the first match, or -1 if not found.
  • replace(regexp|substr, newSubstr|function): Replaces matches with a new substring or the result of a function.
  • match(regexp): Returns an array containing the matches, or null if no match is found. Behavior changes with the g flag.
  • matchAll(regexp) (ES2020): Returns an iterator of all matches, including capturing groups. Requires the g flag.
  • split(separator, limit): Splits a string into an array of substrings, can use a RegExp as a separator.
const text = "Visit W3Schools online!";
const pattern = /w3schools/i;
const position = text.search(pattern);
console.log(position); // Output: 6 (index of 'W')

If a string is passed to search(), it’s implicitly converted to a RegExp: text.search("W3Schools").

const originalText = "Visit Microsoft! Microsoft is great.";
const newText = originalText.replace(/microsoft/ig, "W3Schools");
console.log(newText); // Output: "Visit W3Schools! W3Schools is great."
// 'i' for case-insensitive, 'g' for global (replace all occurrences)

You can also use a string as the first argument for simple replacements: originalText.replace("Microsoft", "W3Schools") (replaces only the first occurrence).

Flags alter the behavior of the regular expression search:

FlagDescription
iIgnore case: Perform case-insensitive matching.
gGlobal search: Find all matches rather than stopping after the first match.
mMultiline mode: Anchors ^ and $ match the start/end of lines, not just the start/end of the string.
sDotAll mode (ES2018): Allows . to match newline characters (\n).
uUnicode mode (ES6): Enables more extensive Unicode support, including matching astral symbols and proper handling of Unicode escapes in patterns.
ySticky mode (ES6): Matches only from the lastIndex position in the target string and does not attempt to match from any later position.

Brackets define character sets:

ExpressionDescription
[abc]Find any one character between the brackets (a, b, or c).
[^abc]Find any character NOT between the brackets.
[0-9]Find any digit from 0 to 9.
[a-z]Find any lowercase letter from a to z.
(x|y)Alternation: Find either ‘x’ or ‘y’.

Metacharacters are characters with special meaning:

MetacharacterDescription
.Matches any single character except newline (unless s flag is used).
\dFind a digit. Equivalent to [0-9].
\DFind a non-digit character.
\sFind a whitespace character (space, tab, newline, etc.).
\SFind a non-whitespace character.
\wFind a word character (alphanumeric plus underscore). Equivalent to [A-Za-z0-9_].
\WFind a non-word character.
\bFind a match at a word boundary (position between a word character and a non-word character).
\BFind a match not at a word boundary.
\nMatches a newline character.
\tMatches a tab character.
\uxxxxFind the Unicode character specified by the hexadecimal number xxxx.

Quantifiers define how many times a character, group, or character class can occur:

QuantifierDescription
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 occurrence of n.
n{X}Matches any string that contains X occurrences of n.
n{X,Y}Matches any string that contains between X and Y occurrences of n.
n{X,}Matches any string that contains at least X occurrences of n.

For a comprehensive guide to RegExp patterns, refer to MDN Web Docs or dedicated regular expression tutorials.

The RegExp object itself has methods for performing matches:

test(string): Searches a string for a pattern. Returns true if a match is found, otherwise false.

const patternTest = /e/;
const resultTest = patternTest.test("The best things in life are free!");
console.log(resultTest); // true

exec(string): Searches a string for a specified pattern and returns an array containing the match information (or null if no match). If the global flag (g) is used, exec() can be called multiple times to find successive matches, updating the lastIndex property of the RegExp object.

const patternExec = /b(est)/;
const resultExec = patternExec.exec("The best things in life are free!");
console.log(resultExec);
// Output: ["best", "est", index: 4, input: "The best things in life are free!", groups: undefined]
// resultExec[0] is the full match, resultExec[1] is the first captured group.

Modern JavaScript allows naming capture groups for better readability:

const datePattern = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const match = datePattern.exec("2023-10-26");
if (match && match.groups) {
console.log(match.groups.year); // "2023"
console.log(match.groups.month); // "10"
console.log(match.groups.day); // "26"
}

Regular expressions are a deep and powerful topic. For a complete reference and more advanced features, consult the MDN Web Docs on JavaScript Regular Expressions and explore online RegExp testers and tutorials.