How to Use Replace with Regex in JavaScript
In JavaScript, you can use the
replace method with a RegExp (regular expression) to find patterns in strings and replace them. Use string.replace(/pattern/flags, replacement) where /pattern/flags is your regex and replacement is the new text or a function.Syntax
The replace method takes two main parts: the pattern to find and the replacement text or function.
- pattern: A
RegExpobject or a string to search for. - flags: Optional modifiers like
gfor global (all matches),ifor case-insensitive. - replacement: The string or function to replace matched parts.
javascript
string.replace(/pattern/flags, replacement)
Example
This example shows how to replace all vowels in a string with a star (*) using a regex with the global flag.
javascript
const text = "Hello World"; const result = text.replace(/[aeiou]/gi, '*'); console.log(result);
Output
H*ll* W*rld
Common Pitfalls
One common mistake is forgetting the g flag, which causes only the first match to be replaced. Another is using a string instead of a regex when you want pattern matching.
Also, when using special characters in regex, they must be escaped.
javascript
const text = "banana"; // Wrong: replaces only first 'a' const wrong = text.replace(/a/, 'o'); console.log(wrong); // bonana // Right: replaces all 'a's const right = text.replace(/a/g, 'o'); console.log(right); // bonono
Output
bonana
bonono
Quick Reference
Use these flags with regex in replace:
g: Replace all matchesi: Case-insensitive matchingm: Multi-line matching
Replacement can be a string or a function for dynamic replacements.
Key Takeaways
Use a regular expression with the global flag
g to replace all matches in a string.The
replace method accepts a regex pattern and a replacement string or function.Without the
g flag, only the first match is replaced.Escape special regex characters when needed to match them literally.
You can use a function as the replacement to customize the output dynamically.