There are two ways to create a regular expression in JavaScript:
const pattern = /hello/i; // 'i' flag for case-insensitive
const pattern = new RegExp('hello', 'i');
i - Case-insensitive matchingg - Global search (find all matches)m - Multiline modes - Dot matches newline characterstest() - Check if pattern existsconst regex = /hello/i;
console.log(regex.test('Hello World')); // true
console.log(regex.test('Goodbye')); // false
exec() - Find match detailsconst regex = /(\w+)@([\w.]+)/;
const match = regex.exec('contact@example.com');
console.log(match[0]); // 'contact@example.com'
console.log(match[1]); // 'contact'
console.log(match[2]); // 'example.com'
match() - Find all matchesconst text = 'cat, dog, cat';
const matches = text.match(/cat/g);
console.log(matches); // ['cat', 'cat']
replace() - Replace matchesconst text = 'Hello World';
const result = text.replace(/world/i, 'JavaScript');
console.log(result); // 'Hello JavaScript'
split() - Split by patternconst text = '2025-02-15';
const parts = text.split(/-/);
console.log(parts); // ['2025', '02', '15']
| Pattern | Matches |
|---|---|
. | Any character except newline |
\d | Digit (0-9) |
\w | Word character (a-z, A-Z, 0-9, _) |
\s | Whitespace |
[abc] | Any of a, b, or c |
[^abc] | Anything except a, b, or c |
a* | Zero or more a’s |
a+ | One or more a’s |
a? | Zero or one a |
a{3} | Exactly 3 a’s |
Email validation pattern:
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailRegex.test('user@example.com')); // true
console.log(emailRegex.test('invalid.email')); // false