How to Replace Text in JavaScript
What you’ll build or solve
You’ll replace text inside a string using simple matches or patterns.
When this approach works best
Replacing text works best when you:
Learn JavaScript on Mimo
- Clean or normalize user input, such as removing extra spaces.
- Update part of a message or template with dynamic data.
- Mask sensitive information like emails or phone numbers.
- Convert specific words or formats in logs or exported data.
Avoid manual string replacement for structured data like JSON. In those cases, parse the data and modify properties directly instead of editing raw text.
Prerequisites
- A browser or Node.js installed
- Basic understanding of strings and variables
No additional setup is required.
Step-by-step instructions
Step 1: Replace the first match with replace()
Use replace(searchValue, newValue) to change the first occurrence.
consttext="I like cats";
constupdated=text.replace("cats","dogs");
console.log(updated);
replace() changes only the first match when you pass a string.
What to look for:
If the same word appears multiple times, only the first one gets replaced.
Step 2: Replace all matches
If you want to replace every occurrence, use one of these options.
Option A: Use replaceAll()
consttext="cats are great. I love cats.";
constupdated=text.replaceAll("cats","dogs");
console.log(updated);
replaceAll() replaces every matching substring.
Option B: Use a global regular expression
consttext="cats are great. I love cats.";
constupdated=text.replace(/cats/g,"dogs");
console.log(updated);
The g flag means global, so all matches are replaced.
Use this option if you need pattern matching later.
Step 3: Use regular expressions for flexible patterns
Regular expressions let you replace patterns instead of fixed words.
Replace all digits:
consttext="Order #1234";
constupdated=text.replace(/\d+/g,"XXXX");
console.log(updated);
Replace case-insensitive matches:
consttext="Cats are great. cats are smart.";
constupdated=text.replace(/cats/gi,"dogs");
console.log(updated);
The i flag makes the match case-insensitive.
Step 4: Replace using a function
You can pass a function as the second argument to compute replacements dynamically.
consttext="Price: 20";
constupdated=text.replace(/\d+/, (match) => {
returnNumber(match)*2;
});
console.log(updated);
The function receives the matched text and returns the replacement value.
This approach helps when you need logic during replacement.
Examples you can copy
Example 1: Mask part of an email
constemail="user@example.com";
constmasked=email.replace(/(.{2}).+(@.+)/,"$1****$2");
console.log(masked);
This keeps the first two characters and the domain.
Example 2: Normalize extra spaces
consttext="Hello world from JavaScript";
constcleaned=text.replace(/\s+/g," ");
console.log(cleaned);
This replaces multiple spaces with a single space.
Example 3: Update placeholders in a template
consttemplate="Hello, NAME!";
constname="Alex";
constmessage=template.replace("NAME",name);
console.log(message);
Example 4: Convert dashes to underscores
constslug="my-blog-post";
constupdated=slug.replace(/-/g,"_");
console.log(updated);
Common mistakes and how to fix them
Mistake 1: Expecting replace() to change all matches
What you might do:
consttext="cat cat cat";
constupdated=text.replace("cat","dog");
Why it breaks:
replace() without a regex only replaces the first match.
Correct approach:
constupdated=text.replaceAll("cat","dog");
Or:
constupdated=text.replace(/cat/g,"dog");
Mistake 2: Forgetting the global flag
What you might do:
consttext="cat cat cat";
constupdated=text.replace(/cat/,"dog");
Why it breaks:
Without g, only the first match is replaced.
Correct approach:
constupdated=text.replace(/cat/g,"dog");
Mistake 3: Trying to modify the original string
What you might do:
lettext="I like cats";
text.replace("cats","dogs");
console.log(text);
Why it breaks:
Strings are immutable. replace() returns a new string and does not change the original.
Correct approach:
text=text.replace("cats","dogs");
console.log(text);
Troubleshooting
- If nothing changes, confirm the search value actually exists in the string.
- If only one match changes, check whether you forgot
replaceAll()or thegflag. - If your regex fails, test it separately to confirm it matches what you expect.
- If case differences block matches, add the
iflag for case-insensitive matching.
Quick recap
- Use
replace()for the first match. - Use
replaceAll()or/pattern/gfor all matches. - Use regular expressions for pattern-based replacements.
- Pass a function when you need dynamic replacement logic.
- Remember that strings are immutable, assign the result back.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot