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.
JavaScript
const text = "I like cats";
const updated = 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()
JavaScript
const text = "cats are great. I love cats.";
const updated = text.replaceAll("cats", "dogs");
console.log(updated);
replaceAll() replaces every matching substring.
Option B: Use a global regular expression
JavaScript
const text = "cats are great. I love cats.";
const updated = 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:
JavaScript
const text = "Order #1234";
const updated = text.replace(/\d+/g, "XXXX");
console.log(updated);
Replace case-insensitive matches:
JavaScript
const text = "Cats are great. cats are smart.";
const updated = 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.
JavaScript
const text = "Price: 20";
const updated = text.replace(/\d+/, (match) => {
return Number(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
JavaScript
const email = "user@example.com";
const masked = email.replace(/(.{2}).+(@.+)/, "$1****$2");
console.log(masked);
This keeps the first two characters and the domain.
Example 2: Normalize extra spaces
JavaScript
const text = "Hello world from JavaScript";
const cleaned = text.replace(/\s+/g, " ");
console.log(cleaned);
This replaces multiple spaces with a single space.
Example 3: Update placeholders in a template
JavaScript
const template = "Hello, NAME!";
const name = "Alex";
const message = template.replace("NAME", name);
console.log(message);
Example 4: Convert dashes to underscores
JavaScript
const slug = "my-blog-post";
const updated = 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:
JavaScript
const text = "cat cat cat";
const updated = text.replace("cat", "dog");
Why it breaks:
replace() without a regex only replaces the first match.
Correct approach:
JavaScript
const updated = text.replaceAll("cat", "dog");
Or:
JavaScript
const updated = text.replace(/cat/g, "dog");
Mistake 2: Forgetting the global flag
What you might do:
JavaScript
const text = "cat cat cat";
const updated = text.replace(/cat/, "dog");
Why it breaks:
Without g, only the first match is replaced.
Correct approach:
JavaScript
const updated = text.replace(/cat/g, "dog");
Mistake 3: Trying to modify the original string
What you might do:
JavaScript
let text = "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:
JavaScript
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