You can replace characters in a string in JavaScript using the replace()
or replaceAll()
method. The replace()
method changes the first match, while replaceAll()
or a global regular expression replaces all occurrences.
Replacing characters in strings is one of the most common operations in web development — from cleaning user inputs to formatting data dynamically. With JavaScript being the language of the web, knowing how to handle text efficiently helps you write cleaner, more optimized code.

Key Takeaways of Replace Characters of a String in JavaScript
Method | Description | Example |
---|---|---|
replace() | Replaces first matching substring | str.replace('a','b') |
replaceAll() | Replaces all matches | str.replaceAll('a','b') |
Regex + /g flag | Replaces all using pattern | str.replace(/a/g,'b') |
What Is the replace()
Method in JavaScript?
The replace()
method in JavaScript is used to replace a part of a string with another substring. It searches the string for a specific value (or a regular expression) and returns a new string with the first match replaced.
Remember — the original string remains unchanged because JavaScript strings are immutable.
Syntax:
string.replace(searchValue, newValue)
searchValue
: The text or pattern you want to replace.newValue
: The text you want to insert instead.
Example:
let text = "apple"; let newText = text.replace("a", "A"); console.log(newText); // "Apple"
Explanation:
Here, only the first occurrence of "a"
is replaced with "A"
. If your string contains multiple "a"
characters, only the first one changes — this is a key limitation of replace()
.

How to Replace All Occurrences of a Character
If you want to replace every instance of a character or substring in JavaScript, there are two main approaches — using replaceAll()
or a regular expression (regex) with the global (/g
) flag.
Example using replaceAll()
The replaceAll()
method was introduced in ES2021 and is the simplest way to replace all occurrences of a substring.
let text = "banana"; let newText = text.replaceAll("a", "o"); console.log(newText); // "bonono"
Explanation:
The method looks for all "a"
characters in "banana"
and replaces them with "o"
. This produces "bonono"
as output.
Tip:replaceAll()
is clean and beginner-friendly, but may not work in older browsers like Internet Explorer.
Example using Regular Expressions
Before replaceAll()
existed, developers used regex with the global flag /g
to achieve the same result.
let text = "banana"; let newText = text.replace(/a/g, "o"); console.log(newText); // "bonono"
Explanation:
The pattern /a/g
tells JavaScript to:
- Find all occurrences of the letter
"a"
. - Replace each with
"o"
.
This method works across all browsers and is still widely used for complex text manipulation.
How to Replace Multiple Different Characters
Sometimes you need to replace different characters or groups of characters in a string — for example, removing unwanted symbols, converting vowels, or cleaning data for URLs.
There are two common approaches:
- Using multiple
replace()
calls (chaining). - Using regular expressions with character sets.
Example 1: Chaining Multiple Replacements
You can call replace()
several times in a row:
let text = "Hello World!"; let newText = text.replace("H", "J").replace("!", "?"); console.log(newText); // "Jello World?"
Explanation:
Each replace()
method acts on the result of the previous one, allowing you to perform multiple substitutions step-by-step.
Example 2: Using a Regex Character Set
You can also use a regex pattern that targets multiple characters at once:
let text = "Hello World!"; let newText = text.replace(/[eo]/g, "x"); console.log(newText); // "Hxllx Wxrld!"
Explanation:
[eo]
is a character set, meaning “match anye
oro
”.- The
/g
flag ensures all matches are replaced. - The result
"Hxllx Wxrld!"
replaces everye
ando
withx
.
This is more efficient and scalable when dealing with several characters at once — for example, sanitizing user input or preparing strings for machine processing.
Bonus: Replace Using a Function (Dynamic Replacement)
You can even pass a callback function to replace()
to dynamically compute the replacement based on each match.
Example:
let text = "I have 2 cats and 3 dogs."; let newText = text.replace(/\d+/g, (num) => num * 2); console.log(newText); // "I have 4 cats and 6 dogs."
Explanation:
Here, every number in the string is replaced by its double.
This technique is extremely useful when transforming dynamic data — such as parsing text, anonymizing information, or formatting numbers.
Pros & Cons: Replace Characters of a String in JavaScript
Method | Pros | Cons |
---|---|---|
replace() | Simple, widely supported | Only replaces first occurrence |
replaceAll() | Cleaner, replaces all | Not supported in very old browsers |
Regex /g | Flexible, powerful | Slightly complex syntax |
Practical Uses of Replace Characters of a String in JavaScript
- Email Censorship in Social Platforms:
A popular social media company wants to censor email addresses shared in public posts to protect user privacy. They replace characters to hide sensitive information.
By implementing this, they effectively protect users’ email addresses from being visible in the public domainlet email = "contact@example.com";
let censoredEmail = email.replace(/@.*$/, "@.com");
console.log(censoredEmail); // Output: contact@.com
- Keyword Highlighting in Search Engines:
A well-known search engine uses string replacement to highlight search keywords in result snippets. This feature helps users quickly locate relevant information.
This method enhances readability, making it easier for users to access pertinent details in search results.
let snippet = "JavaScript String Replace can be really helpful.";
let keyword = "Replace";
let highlightedSnippet = snippet.replace(keyword, `${keyword}`);
console.log(highlightedSnippet); // Output: JavaScript String Replace can be really helpful.
- Username Sanitisation on E-commerce Platforms:
A leading e-commerce business sanitises usernames by replacing special characters to maintain a consistent format across their platform.
Through this process, the platform ensures that all usernames adhere to the same set of rules, making the user experience more streamlined.
let username = "user@name!123";
let sanitizedUsername = username.replace(/[@!]/g, "_");
console.log(sanitizedUsername); // Output: user_name_123
Replace Characters of a String in JavaScript Questions
- How can you replace multiple characters at once in a JavaScript string without using a loop?
Using the `replace()` method along with a Regular Expression (RegEx), you can replace multiple characters without resorting to a loop. Here’s a code snippet to illustrate:let str = "h3ll0 w0rld";
let newStr = str.replace(/[30]/g, function(match) {
return match === '3' ? 'e' : 'o';
});
console.log(newStr); // Output: "hello world" - Is there a method for replacing characters that ignore case sensitivity?
Indeed! By using the `i` flag in your Regular Expression within the `replace()` method, case-insensitive replacements are possible.let str = "Hello World";
let newStr = str.replace(/hello/i, "Hi");
console.log(newStr); // Output: "Hi World" - Can you replace a character at a specific index in a string?
Of course! You can replace a character at a specific index by converting the string into an array, modifying the desired index, and then joining it back into a string.let str = "world";
let index = 1;
let newStr = str.split('');
newStr[index] = 'a';
console.log(newStr.join('')); // Output: "warld" - What’s the most efficient way to replace characters when working with large strings?
Efficiency comes with using RegEx as it provides a powerful mechanism for matching patterns and can process large strings quickly, without the need for looping. - How do you replace a series of characters but only within a specific substring?
First, isolate the substring, perform the replacement, and then reconstruct the overall string.let str = "abcXYZdef";
let subStr = str.substring(3, 6).replace(/X/, 'L');
let newStr = str.substring(0, 3) + subStr + str.substring(6);
console.log(newStr); // Output: "abcLYZdef" - Can JavaScript’s `replace()` method handle emoji or special characters?
Absolutely, as long as the special characters or emojis are properly encoded within the RegEx. Utilizing Unicode escapes like `u{1F600}` caters to emojis. - Is it possible to replace characters using a function rather than a simple string?
Yes, by passing a function to the `replace()` method, the replacement can be dynamically determined.let str = "1a2b3c";
let newStr = str.replace(/d/g, match => `[${match}]`);
console.log(newStr); // Output: "[1]a[2]b[3]c" - How to replace characters conditionally, based on their position?
By using a combination of `replace()` and a conditional within a callback function, replacement based on position is achievable.let str = "abcd";
let newStr = str.replace(/./g, (match, offset) => offset % 2 === 0 ? match.toUpperCase() : match);
console.log(newStr); // Output: "AbCd
Discover our AI-powered js online compiler, where you can instantly write, run, and test your code. Our intelligent compiler simplifies your coding experience, offering real-time suggestions and debugging tips, streamlining your journey from coding novice to expert with ease. Explore it today and boost your coding skills!
Download our free JavaScript Cheat Sheet to speed up your learning!
Conclusion
Replace Characters of a String in JavaScript enhances your coding skills by enabling string manipulation mastery. It’s rewarding and versatile, letting you solve real-world problems with elegance. Dive in, experiment, and grow your expertise. For more programming insights, explore languages like Java, Python, and C++ with Newtum.
Edited and Compiled by
This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.