Problem:
When using JavaScript's built-in replace() method to replace a substring, only the first occurrence is replaced, as seen in this example:
<code class="javascript">var string = "Test abc test test abc test test test abc test test abc"; string = string.replace('abc', ''); // Only replaces the first 'abc' occurrence</code>
How can we replace all occurrences of a substring in JavaScript?
Solution:
Modern Browsers:
Modern browsers support the String.replaceAll() method, which replaces all occurrences of a substring with a specified replacement:
<code class="javascript">string = string.replaceAll('abc', ''); // Replaces all 'abc' occurrences</code>
Custom Function:
For older or legacy browsers that don't support String.replaceAll(), we can use a custom function:
<code class="javascript">function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } function escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\]/g, '\$&'); }</code>
Usage:
<code class="javascript">console.log(replaceAll(string, 'abc', '')); // Replaces all 'abc' occurrences</code>
Note:
The above is the detailed content of How to Replace All Instances of a Specific String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!