When working with strings in JavaScript—whether it’s sanitizing user input, updating UI text dynamically, or reformatting information—one of the most common and essential operations is replacing string content. Despite its familiarity, string replacement in JavaScript offers a surprising range of nuances and methods that make it a powerful tool for developers when used effectively.
TL;DR
If you’re looking to modify strings in JavaScript, there are several methods at your disposal. The String.prototype.replace() method is the most common, with support for both plain text and regular expressions. String.prototype.replaceAll() is newer but incredibly handy for global replacements without regular expressions. Advanced techniques involving regex offer significant flexibility, especially with callback functions, enabling complex conditional replacements with ease.
1. The Basics: Using replace()
The replace() method is the foundation of string replacement in JavaScript. It’s simple, effective, and supported across all browsers.
Its basic syntax looks like this:
let newString = oldString.replace(searchValue, newValue);
What can searchValue be?
- A plain string (replaces only the first occurrence)
- A regular expression (more powerful and flexible)
Example using a plain string:
let text = "Hello world";
let result = text.replace("world", "JavaScript");
console.log(result); // "Hello JavaScript"
However, this only replaces the first instance. To replace all occurrences, you’ll either need a regular expression with the /g flag or use replaceAll() (we’ll get to that shortly).
2. Regular Expressions: Unleashing the Full Power of replace()
Using regular expressions with replace() lets you perform more dynamic and complex replacements.
Example: Replace all numbers in a string with ‘#’.
let phone = "My number is 123-456-7890";
let masked = phone.replace(/\d/g, "#");
console.log(masked); // "My number is ###-###-####"
The /\d/g regex matches every digit because of the g (global) flag. Without this flag, only the first digit would be replaced.
Special Regex Features
With regular expressions, you can use advanced tokens and groups for fine-grained control.
Capturing groups can be used to preserve parts of the match:
let date = "2024-06-01";
let formatted = date.replace(/(\d{4})-(\d{2})-(\d{2})/, "$2/$3/$1");
console.log(formatted); // "06/01/2024"
This is extremely useful for formatting tasks and extracting structured information from unstructured text.
3. Introducing replaceAll()
For years, developers had to rely on regular expressions when trying to replace all occurrences of a substring. But in ES2021, JavaScript introduced replaceAll(), a method specifically designed to make this easier.
Syntax:
let result = string.replaceAll(searchValue, newValue);
You can use replaceAll() with static strings only (not regex with flags), but it simplifies code readability and prevents regex-related bugs.
Example:
let text = "apple, banana, apple, cherry";
let newText = text.replaceAll("apple", "orange");
console.log(newText); // "orange, banana, orange, cherry"
This makes simple replacements cleaner and easier to read.
4. Function-Based Replacement
One of the most robust techniques in JavaScript string replacement is using a function as the second argument in replace(). This allows for dynamic, context-aware adjustments during the replacement process.
Example: Censor offensive words
let text = "What the heck is that darn thing?";
let censored = text.replace(/\b(heck|darn)\b/gi, function(match) {
return "*".repeat(match.length);
});
console.log(censored);
// "What the is that thing?"
By using a function, the replacement can vary depending on the matched text. This is greatly beneficial in a wide range of applications, from natural language processing to generating file-safe names from arbitrary input.
5. Template Strings and Manual Replacement
In use cases where you need placeholder substitution ({{name}} patterns, for example), you can roll your own replacement function using regex and objects.
Example:
let template = "Hello, {{name}}! Your balance is {{balance}}.";
let data = { name: "Alice", balance: "$250" };
let output = template.replace(/{{(.*?)}}/g, (match, key) => data[key.trim()] || "");
console.log(output);
// "Hello, Alice! Your balance is $250."
This is essentially a lightweight templating engine. With a few extra features, it can even replace simple libraries that only do string interpolation.
6. Edge Cases & Gotchas
While these methods are powerful, it’s important to be aware of potential pitfalls:
- Backslashes: If your replacement string uses backslashes (like
\n), escaping them properly is critical. - Regex confusion: Mixing string and regex syntax leads to bugs. Always double-check your flags and patterns.
- Complex object access: With template strings, nested objects aren’t accessible without custom logic.
Therefore, choose the right method based on readability, performance, and edge-case handling.
7. Performance Considerations
The performance impact of string replacement usually depends on how frequently and how extensively the operation is done. For occasional, low-frequency replacements, the method you choose usually won’t matter much in terms of speed. However:
- Repeated
replace()without/g: This adds overhead since you’re calling multiple replacements manually. - Regex with large texts: Regex can slow things down if overused or poorly constructed.
replaceAll()may be faster for multiple matches than a global regex—at least in modern JS engines.
For maximum efficiency in real-time environments (e.g., input sanitization while typing), prefer the simplest functioning method and benchmark if necessary.
Conclusion
JavaScript offers a wide toolkit for developers when it comes to string replacement. Whether you need basic substitutions, complex conditional formatting, or placeholder templating, the language’s string API lets you mix intuitive simplicity with deep functionality.
As string manipulation plays a crucial role in web development, mastering these methods enables you to write secure, clean, and maintainable code—turning mundane replacements into seamless transformations.
Happy coding!