How to Replace Multiple Characters in a String in JavaScript
A common string manipulation task is to replace a set of different characters with a single, uniform character. For example, you might want to replace various delimiters like dots, underscores, and hyphens with a space to normalize a string. The most efficient and powerful way to do this is with the String.prototype.replace() method using a regular expression with a character set.
This guide will teach you how to use this regex-based approach, and also cover the alternative of chaining multiple replaceAll() calls for situations where you might want to avoid regular expressions.
The Core Method (Recommended): replace() with a Character Set
The most concise and performant way to replace multiple, different characters is to use a single regular expression that contains a character set ([...]). This allows you to define a group of characters to match in a single pass.
Problem: you have a string with a mix of different separators, and you want to replace all of them with a single space.
// Problem: How to replace '.', '_', and '-' all at once?
let messyString = 'file.name_with-separators';
Solution:
let messyString = 'file.name_with-separators';
// The regex /[._-]/g matches any dot, underscore, or hyphen, globally.
let cleanString = messyString.replace(/[._-]/g, ' ');
console.log(cleanString);
Output:
file name with separators
This single line of code is the most efficient way to solve the problem.
How the Character Set Works
Let's break down the pattern /[._-]/g:
/ ... /g: The forward slashes denote a regular expression, and thegis the global flag, which is essential for replacing all occurrences, not just the first one.[._-]: This is the character set. It tells the regex engine to match any single character that is found inside the brackets. In this case, it will match a literal dot (.), an underscore (_), or a hyphen (-).
The replace() method finds every character that matches this set and replaces it with a space.
You can add any number of characters to the set. For example, to also replace spaces and question marks, you would use /[._\s?-]/g. (\s is a special character for whitespace).
An Alternative (Verbose) Method: Chaining replaceAll()
If you prefer to avoid regular expressions, you can achieve the same result by chaining multiple calls to the String.prototype.replaceAll() method.
Problem: same as before: replace all dots, underscores, and hyphens with a space.
Solution:
let messyString = 'file.name_with-separators';
let cleanString = messyString
.replaceAll('.', ' ')
.replaceAll('_', ' ')
.replaceAll('-', ' ');
console.log(cleanString);
Output:
file name with separators
Comparison of Methods
- Readability: The
replaceAll()chain can be more readable for developers who are not comfortable with regular expressions. - Performance: For a small number of replacements, the difference is negligible. However, the regular expression method is more performant because it only iterates through the string once. The chained method iterates through the string three separate times.
- Flexibility: Regular expressions are far more powerful. For example, you cannot easily "replace all whitespace characters" with the
replaceAllchain, but it's trivial with a regex (/\s/g).
Conclusion
Replacing multiple different characters in a string is a task perfectly suited for a regular expression.
- The recommended best practice is to use
string.replace(/[abc]/g, '...')with a character set ([...]). This is the most efficient and scalable solution. - An alternative for simpler cases is to chain multiple
replaceAll()calls. This can be more readable if you are only replacing two or three specific characters and want to avoid regex.
For most use cases, the single regular expression is the superior and more professional choice.