ES6 - RegExp
ES6+ - Regular Expressions (RegExp)
Section titled “ES6+ - Regular Expressions (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.
Creating Regular Expressions
Section titled “Creating Regular Expressions”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 matchconst 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 /\/.Regular Expression Flags (Attributes)
Section titled “Regular Expression Flags (Attributes)”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.
| Flag | Name | Description |
|---|---|---|
g | Global match | Finds all matches rather than stopping after the first match. |
i | Ignore case | Makes the match case-insensitive. |
m | Multiline | Treats 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. |
u | Unicode (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}. |
y | Sticky (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. |
s | DotAll / Singleline (ES2018) | Allows the dot (.) metacharacter to match newline characters (\n, \r, etc.). Without s, . matches any character except newlines. |
Basic RegExp Syntax Components
Section titled “Basic RegExp Syntax Components”Character Classes and Sets ([]):
Section titled “Character Classes and Sets ([]):”Brackets are used to define a set of characters to match.
| Expression | Description |
|---|---|
[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:
Section titled “Quantifiers:”Quantifiers specify how many times a character, group, or character class must be present in the input for a match to be found.
| Quantifier | Description |
|---|---|
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. |
Anchors and Boundaries:
Section titled “Anchors and Boundaries:”| Anchor | Description |
|---|---|
^ | 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). |
\b | Word boundary: Matches a position between a word character (\w) and a non-word character (\W) or start/end of string. |
\B | Non-word boundary. |
Grouping and Capturing (()):
Section titled “Grouping and Capturing (()):”Parentheses group parts of a regular expression and create capturing groups. The matched substring can be remembered and accessed later.
(pattern): Capturing group. Matchespatternand captures the match.(?:pattern): Non-capturing group. Matchespatternbut does not capture the match.(?<name>pattern): Named capturing group (ES2018). Captures the match and assigns it togroups.name.
Special Characters (Metacharacters):
Section titled “Special Characters (Metacharacters):”These characters have special meanings in regular expressions. To match them literally, they usually need to be escaped with a backslash (\).
| Character | Description |
|---|---|
. | Matches any single character except newline (unless s flag is used). |
\d | Matches any digit. Equivalent to [0-9]. |
\D | Matches any non-digit. Equivalent to [^0-9]. |
\w | Matches any word character (alphanumeric + underscore). Equivalent to [A-Za-z0-9_]. |
\W | Matches any non-word character. Equivalent to [^A-Za-z0-9_]. |
\s | Matches any whitespace character (space, tab, newline, etc.). |
\S | Matches any non-whitespace character. |
\t | Matches a tab character. |
\n | Matches a newline character. |
\r | Matches a carriage return character. |
\uxxxx | Matches the Unicode character specified by the hexadecimal number xxxx. |
\p{...}, \P{...} | Unicode property escapes (requires u flag, e.g., \p{Script=Latn}). |
Alternation (|):
Section titled “Alternation (|):”The | (OR) operator allows matching one of several expressions. E.g., /cat|dog/ matches ‘cat’ or ‘dog’.
RegExp Instance Properties
Section titled “RegExp Instance Properties”| Property | Description |
|---|---|
RegExp.prototype.flags (ES6) | A string containing the flags of the RegExp object (e.g., “giu”). |
RegExp.prototype.global | Boolean: Whether the g flag is set. |
RegExp.prototype.ignoreCase | Boolean: Whether the i flag is set. |
RegExp.prototype.multiline | Boolean: 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.source | The text of the pattern (without flags). |
RegExp.prototype.lastIndex | An 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 and String Methods
Section titled “RegExp and String Methods”RegExp Methods:
Section titled “RegExp Methods:”RegExp.prototype.test(str): Executes a search for a match between a regular expression and a specified string. Returnstrueif a match is found,falseotherwise.RegExp.prototype.exec(str): Executes a search for a match in a specified string. Returns an array of information about the match (ornullif no match). If the global flag (g) is set,exec()updateslastIndexand can be called repeatedly to find all matches.
String Methods that use RegExp:
Section titled “String Methods that use RegExp:”String.prototype.match(regexp): Retrieves the result of matching a string against a regular expression. Ifregexphas thegflag, it returns an array of all matches ornull. Withoutg, it returns the same asregexp.exec(string).String.prototype.matchAll(regexp)(ES2020): Returns an iterator of all results matching a string against a regular expression, including capturing groups. Requires thegflag on theregexp.String.prototype.replace(regexp|substr, newSubstr|function): Returns a new string with some or all matches of a pattern replaced by a replacement. Theregexpcan be a string or aRegExpobject. 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 thisStringobject. Returns the index of the first match, or -1 if no match is found. Ignores thegflag.String.prototype.split(separator|regexp[, limit]): Splits aStringobject into an array of strings by separating the string into substrings, using a specified separator string or regular expression.
Example Usage:
Section titled “Example Usage:”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 markconsole.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.