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

How to Replace All Occurrences of a String in JavaScript?

Mary-Kate Olsen
Release: 2024-10-25 08:13:03
Original
818 people have browsed it

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

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

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!

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!