JavaScript Regular Expressions Syntax Cheat Sheet
Regular Expressions (RegEx) are patterns used to match character combinations in strings. In JavaScript, regular expressions are objects that can be created using the RegExp constructor or by using a literal notation.
Creating Regular Expressions
Literal Notation
const regex = /pattern/flags;Constructor Notation
const regex = new RegExp('pattern', 'flags');Common Flags
g: Global search.i: Case-insensitive search.m: Multi-line search.s: Dot matches newline characters (ES2018).u: Unicode; treat a pattern as a sequence of Unicode code points.y: Sticky; matches only from the index indicated by thelastIndexproperty of this regular expression.
Special Characters
.: Matches any single character except newline.\d: Matches any digit (0-9).\D: Matches any non-digit.\w: Matches any word character (alphanumeric & underscore).\W: Matches any non-word character.\s: Matches any whitespace character.\S: Matches any non-whitespace character.\b: Matches a word boundary.\B: Matches a non-word boundary.^: Matches the beginning of the string or line.$: Matches the end of the string or line.
Quantifiers
*: Matches 0 or more occurrences of the preceding element.+: Matches 1 or more occurrences of the preceding element.?: Matches 0 or 1 occurrence of the preceding element.{n}: Matches exactlynoccurrences of the preceding element.{n,}: Matchesnor more occurrences of the preceding element.{n,m}: Matches betweennandmoccurrences of the preceding element.
Character Classes
[abc]: Matches any one of the charactersa,b, orc.[^abc]: Matches any character excepta,b, orc.[a-z]: Matches any character fromatoz.[A-Z]: Matches any character fromAtoZ.[0-9]: Matches any digit from0to9.
Grouping and Alternation
(abc): Matches the exact sequenceabc.a|b: Matches eitheraorb.(a|b): Matches eitheraorb.
Assertions
(?=...): Positive lookahead assertion.(?!...): Negative lookahead assertion.(?<=...): Positive lookbehind assertion (ES2018).(?<!...): Negative lookbehind assertion (ES2018).
Escaping Special Characters
Use a backslash (\) to escape special characters.
const regex = /a\+b/; // Matches "a+b"Using Regular Expressions in JavaScript
test(): Tests for a match in a string. Returns true or false.
const regex = /hello/;
console.log(regex.test('hello world')); // trueexec(): Executes a search for a match in a string. Returns an array of results or null.
const regex = /hello/;
const result = regex.exec('hello world');
console.log(result); // ["hello", index: 0, input: "hello world", groups: undefined]String Methods with Regular Expressions
-
match(): Returns an array containing all matches ornull.const str = 'hello world'; const regex = /o/g; console.log(str.match(regex)); // ["o", "o"] -
matchAll(): Returns an iterator of all results matching a string against a regular expression, including capturing groups.const str = 'hello world'; const regex = /o/g; console.log(Array.from(str.matchAll(regex))); // [["o"], ["o"]] -
replace(): Replaces matches in a string with a replacement.const str = 'hello world'; const regex = /world/; console.log(str.replace(regex, 'JavaScript')); // "hello JavaScript" -
search(): Searches for a match in a string and returns the index of the match.const str = 'hello world'; const regex = /world/; console.log(str.search(regex)); // 6 -
split(): Splits a string into an array of substrings.const str = 'hello world'; const regex = /\s/; console.log(str.split(regex)); // ["hello", "world"]
Examples
Validate Email
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test('[email protected]')); // true
console.log(emailRegex.test('invalid-email')); // falseExtract Domain from URL
const url = 'https://www.example.com/path';
const domainRegex = /https?:\/\/(www\.)?([^\/]+)/;
const match = url.match(domainRegex);
console.log(match[2]); // "example.com"Match All Words
const text = 'This is a test.';
const words = text.match(/\b\w+\b/g);
console.log(words); // ["This", "is", "a", "test"]This cheat sheet provides an overview of JavaScript regular expressions syntax and usage. Regular expressions are a powerful tool for text processing and data validation in JavaScript.