Home > Web Front-end > JS Tutorial > body text

How to Replace All Occurrences of a String in JavaScript

Barbara Streisand
Release: 2024-10-24 14:12:02
Original
692 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

Therefore, the updated replaceAll() function becomes:

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!