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

How to Replace All Instances of a Specific String in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 14:30:02726browse

How to Replace All Instances of a Specific String in JavaScript?

How to Replace All Occurrences of a String in JavaScript

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:

Using String.replaceAll()

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>

For Older/Legacy Browsers

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 escapeRegExp() function escapes special characters in the search string to ensure accurate matching.
  • The g flag in the regular expression ensures all occurrences are replaced.

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!

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