JavaScript RegExp
JavaScript Regular Expressions
Section titled “JavaScript Regular Expressions”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.
What Is a Regular Expression?
Section titled “What Is a Regular Expression?”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.
Syntax
Section titled “Syntax”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):
w3schoolsis the pattern to search for.iis 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, ornullif no match is found. Behavior changes with thegflag.matchAll(regexp)(ES2020): Returns an iterator of all matches, including capturing groups. Requires thegflag.split(separator, limit): Splits a string into an array of substrings, can use a RegExp as a separator.
Using String.search() with a RegExp
Section titled “Using String.search() with a RegExp”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").
Using String.replace() with a RegExp
Section titled “Using String.replace() with a RegExp”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).
Regular Expression Flags (Modifiers)
Section titled “Regular Expression Flags (Modifiers)”Flags alter the behavior of the regular expression search:
| Flag | Description |
|---|---|
i | Ignore case: Perform case-insensitive matching. |
g | Global search: Find all matches rather than stopping after the first match. |
m | Multiline mode: Anchors ^ and $ match the start/end of lines, not just the start/end of the string. |
s | DotAll mode (ES2018): Allows . to match newline characters (\n). |
u | Unicode mode (ES6): Enables more extensive Unicode support, including matching astral symbols and proper handling of Unicode escapes in patterns. |
y | Sticky mode (ES6): Matches only from the lastIndex position in the target string and does not attempt to match from any later position. |
Regular Expression Patterns
Section titled “Regular Expression Patterns”Brackets define character sets:
| Expression | Description |
|---|---|
[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:
| Metacharacter | Description |
|---|---|
. | Matches any single character except newline (unless s flag is used). |
\d | Find a digit. Equivalent to [0-9]. |
\D | Find a non-digit character. |
\s | Find a whitespace character (space, tab, newline, etc.). |
\S | Find a non-whitespace character. |
\w | Find a word character (alphanumeric plus underscore). Equivalent to [A-Za-z0-9_]. |
\W | Find a non-word character. |
\b | Find a match at a word boundary (position between a word character and a non-word character). |
\B | Find a match not at a word boundary. |
\n | Matches a newline character. |
\t | Matches a tab character. |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx. |
Quantifiers define how many times a character, group, or character class can occur:
| 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 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.
Using the RegExp Object Methods
Section titled “Using the RegExp Object Methods”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); // trueexec(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.Advanced: Named Capture Groups (ES2018)
Section titled “Advanced: Named Capture Groups (ES2018)”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"}Further Learning
Section titled “Further Learning”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.