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

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

Patricia Arquette
Release: 2024-10-24 14:30:02
Original
725 people have browsed it

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

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

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

Usage:

<code class="javascript">console.log(replaceAll(string, 'abc', '')); // Replaces all 'abc' occurrences</code>
Copy after login

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!

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!