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

How to Replace All Occurrences of a String in JavaScript

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 14:12:02781browse

How to Replace All Occurrences of a String in JavaScript

Replacing Multiple Occurrences of a String in JavaScript

You may find yourself needing to replace multiple occurrences of a string in JavaScript, but the standard string.replace() method only removes the first instance. How can you ensure all occurrences are replaced?

Modern Solution (ES2021 )

Modern browsers now support the String.replaceAll() method, which natively allows you to replace all instances of a string. Simply use the syntax:

<code class="js">string = string.replaceAll('abc', '');</code>

Legacy Solution for Older Browsers

For older browsers, you can use a regular expression with the g (global) flag:

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

Escaping Special Characters

Regular expressions contain special characters, so be cautious when passing a variable for the find argument. Use the escapeRegExp() function to safely escape any special characters:

<code class="js">function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\]/g, '\$&');
}</code>

Therefore, the updated replaceAll() function becomes:

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

This solution ensures all occurrences of the specified string are replaced despite browser compatibility.

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