How to Create Regex in JavaScript: Syntax and Examples
In JavaScript, you create a regular expression using either the
/pattern/flags literal syntax or the RegExp constructor. Both ways let you define patterns to search or match text.Syntax
There are two ways to create a regular expression in JavaScript:
- Literal syntax: Use slashes
/pattern/flagswherepatternis the regex andflagsare optional modifiers. - Constructor syntax: Use
new RegExp('pattern', 'flags')where both pattern and flags are strings.
Flags like g (global), i (ignore case), and m (multiline) change how the regex works.
javascript
// Literal syntax const regex1 = /hello/i; // Constructor syntax const regex2 = new RegExp('hello', 'i');
Example
This example shows how to create a regex to find the word "hello" ignoring case, then test if it matches a string.
javascript
const regex = /hello/i; const text = 'Hello world!'; const result = regex.test(text); console.log(result);
Output
true
Common Pitfalls
Common mistakes include:
- Forgetting to escape special characters like
.or?in the pattern. - Using the constructor syntax without double escaping backslashes (e.g.,
\\dinstead of\d). - Confusing flags or forgetting them when needed.
javascript
// Wrong: missing escape for dot const wrong = /www.example.com/; console.log(wrong.test('www.example.com')); // true because dot means any char // Right: escape dot const right = /www\.example\.com/; console.log(right.test('www.example.com')); // true // Constructor needs double escape const regex = new RegExp('\\d+', 'g'); console.log('123abc'.match(regex)); // ['123']
Output
true
true
[ '123' ]
Quick Reference
| Syntax | Description |
|---|---|
| /pattern/flags | Regex literal with optional flags |
| new RegExp('pattern', 'flags') | Regex constructor with pattern and flags as strings |
| g | Global search (find all matches) |
| i | Ignore case |
| m | Multiline mode |
| \d | Matches any digit (0-9) |
| \w | Matches any word character (letters, digits, underscore) |
| . | Matches any single character except newline |
Key Takeaways
Create regex in JavaScript using literal syntax /pattern/flags or RegExp constructor.
Use flags like g, i, and m to modify regex behavior.
Escape special characters properly to avoid unexpected matches.
Constructor syntax requires double escaping backslashes.
Test regex with methods like test() or match() to check matches.