Replacing All Occurrences of a String in JavaScript
When attempting to replace all instances of a specific string in JavaScript, simply using the replace() method may only modify the first occurrence. To replace all instances effectively, consider the following approaches:
Modern Browsers (August 2020 and Later)
<code class="js">str.replaceAll(find, replace);</code>
Older/Legacy Browsers
<code class="js">str.replace(new RegExp(find, 'g'), replace);</code>
<code class="js">function escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\]/g, '\$&'); } function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); }</code>
This function escapes special characters in the search string to prevent unexpected replacements.
The above is the detailed content of How to Replace All Occurrences of a String Effectively in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!