Home  >  Article  >  Web Front-end  >  How to Replace All Occurrences of a String in JavaScript?

How to Replace All Occurrences of a String in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-25 08:13:03819browse

How to Replace All Occurrences of a String in JavaScript?

Replacing All Instances of a String in JavaScript

Given a string like "Test abc test test abc test test test abc test test abc", replacing the first occurrence of "abc" using string.replace('abc', '') is insufficient. This question tackles how to replace all occurrences of a string in JavaScript.

Modern Solution (ECMAScript 2021 and Later):

For modern browsers that support the ECMAScript 2021 specification, you can utilize the String.replaceAll() method:

<code class="javascript">str = str.replaceAll('abc', '');</code>

Legacy Browser Solution:

For older or legacy browsers that lack String.replaceAll(), the following custom function can be employed:

<code class="javascript">function replaceAll(str, find, replace) {
  return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\]/g, '\$&'); // $& means the whole matched string
}</code>

This pattern was refined several times, ultimately resulting in the replaceAll() function above, which accommodates string arguments in the find parameter by pre-processing them to escape special characters.

The above is the detailed content of How to Replace All Occurrences of a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn