How to Replace Text in a String in JavaScript Easily
In JavaScript, you can replace text in a string using the
replace() method. It takes the text to find and the text to replace it with as arguments. For replacing all occurrences, use a regular expression with the global flag /g.Syntax
The basic syntax of the replace() method is:
string.replace(searchValue, newValue)
Where:
searchValueis the text or pattern you want to replace.newValueis the text you want to use as a replacement.
If searchValue is a string, only the first occurrence is replaced. To replace all occurrences, use a regular expression with the global flag /g.
javascript
const text = 'Hello world! Hello!'; const newText = text.replace('Hello', 'Hi'); console.log(newText);
Output
Hi world! Hello!
Example
This example shows how to replace the first occurrence of a word and how to replace all occurrences using a regular expression with the global flag.
javascript
const text = 'Hello world! Hello everyone!'; // Replace only the first 'Hello' const firstReplace = text.replace('Hello', 'Hi'); console.log(firstReplace); // Replace all 'Hello' using regex with global flag const allReplace = text.replace(/Hello/g, 'Hi'); console.log(allReplace);
Output
Hi world! Hello everyone!
Hi world! Hi everyone!
Common Pitfalls
One common mistake is expecting replace() with a string to replace all occurrences, but it only replaces the first one. Another is not using the global flag /g in regular expressions when you want to replace all matches.
Also, when using special characters in searchValue as a regex, you must escape them properly.
javascript
const text = 'apple apple apple'; // Wrong: only replaces first 'apple' const wrong = text.replace('apple', 'orange'); console.log(wrong); // orange apple apple // Right: replace all using regex with global flag const right = text.replace(/apple/g, 'orange'); console.log(right); // orange orange orange
Output
orange apple apple
orange orange orange
Quick Reference
| Method | Description | Example |
|---|---|---|
| replace(searchValue, newValue) | Replaces first match of searchValue | 'hello'.replace('h', 'H') → 'Hello' |
| replace(/pattern/g, newValue) | Replaces all matches using regex with global flag | 'hello hello'.replace(/h/g, 'H') → 'Hello Hello' |
Key Takeaways
Use string.replace(searchValue, newValue) to replace text in JavaScript strings.
Only the first occurrence is replaced when searchValue is a string.
Use a regular expression with the global flag (/g) to replace all occurrences.
Escape special characters in regex patterns to avoid errors.
Test your replacements to ensure they work as expected.