How to Use Regex in JavaScript: Syntax and Examples
In JavaScript, you use
RegExp objects or regex literals like /pattern/flags to create regular expressions. You can test patterns with test(), find matches with match(), or replace text using replace() methods.Syntax
A regular expression in JavaScript can be created using a regex literal or the RegExp constructor.
- Regex literal:
/pattern/flagswherepatternis the search pattern andflagsmodify the search behavior. - RegExp constructor:
new RegExp('pattern', 'flags')useful when pattern is dynamic. - Common flags:
gfor global search,ifor case-insensitive,mfor multiline.
javascript
/abc/i; const regex = new RegExp('abc', 'i');
Example
This example shows how to test if a string contains the word 'hello' ignoring case, and how to replace it with 'hi'.
javascript
const regex = /hello/i; const text = 'Hello world!'; // Test if 'hello' exists const hasHello = regex.test(text); console.log(hasHello); // true // Replace 'hello' with 'hi' const newText = text.replace(regex, 'hi'); console.log(newText); // 'hi world!'
Output
true
hi world!
Common Pitfalls
One common mistake is forgetting the global flag g when you want to replace all matches, not just the first. Another is not escaping special characters like . or ? when you want to match them literally.
Also, using the test() method on a regex with the g flag can give unexpected results because it remembers the last index.
javascript
const regexWrong = /hello/; const text = 'hello hello'; // Only replaces first 'hello' console.log(text.replace(regexWrong, 'hi')); // 'hi hello' const regexRight = /hello/g; // Replaces all 'hello' console.log(text.replace(regexRight, 'hi')); // 'hi hi' const regexTest = /hello/g; console.log(regexTest.test(text)); // true console.log(regexTest.test(text)); // false (because lastIndex moved) // Fix: create new regex or reset lastIndex regexTest.lastIndex = 0; console.log(regexTest.test(text)); // true
Output
hi hello
hi hi
true
false
true
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Regex literal | Create regex with slashes | /abc/i |
| RegExp constructor | Create regex dynamically | new RegExp('abc', 'i') |
| Flags | Modify search behavior | g (global), i (ignore case), m (multiline) |
| test() | Check if pattern exists | /abc/.test('abc') // true |
| match() | Get matches from string | 'abc123'.match(/\d+/) // ['123'] |
| replace() | Replace matched text | 'abc'.replace(/a/, 'x') // 'xbc' |
Key Takeaways
Use regex literals or RegExp constructor to create patterns in JavaScript.
Remember to use flags like 'g' for global and 'i' for case-insensitive searches.
Use test(), match(), and replace() methods to work with regex on strings.
Escape special characters when you want to match them literally.
Be cautious with the 'g' flag and test() method as it maintains state between calls.