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

How to Replace All Occurrences of a String Effectively in JavaScript?

Linda Hamilton
Release: 2024-10-25 04:23:29
Original
371 people have browsed it

How to Replace All Occurrences of a String Effectively in JavaScript?

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)

  • Utilize the String.replaceAll() method:
<code class="js">str.replaceAll(find, replace);</code>
Copy after login

Older/Legacy Browsers

  • Construct a regular expression with the 'g' (global) flag:
<code class="js">str.replace(new RegExp(find, 'g'), replace);</code>
Copy after login
  • Employ the escapeRegExp function to handle potential special characters in the search string:
<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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template