Home > Article > Web Front-end > How to Replace Multiple Characters in a String with a Single `replace()` Call in JavaScript?
Replacing Multiple Characters with a Single Replace Call
In JavaScript, you may occasionally encounter the need to replace multiple characters in a string. While chaining multiple replace() calls may suffice for some scenarios, a more efficient and concise approach is leveraging the OR operator (|).
To simultaneously replace multiple characters, you can use the OR operator within the regular expression passed as an argument to the replace() method. For instance, to replace all instances of '_' with a space and '#' with nothing, use the following syntax:
string.replace(/#|_/g, '');
In this expression, the OR operator combines two character classes:
By placing them inside brackets and separating them with the OR operator, the replace() method will replace any character that matches either pattern.
Example: var string = '#Please send_an_information_pack_to_the_following_address:'; string = string.replace(/#|_/g, ''); console.log(string);
Output:
Please send an information pack to the following address:
The above is the detailed content of How to Replace Multiple Characters in a String with a Single `replace()` Call in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!