Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

This tutorial will help you to replace the same strings or words from your string data. we will see two methods to replace all occurrences in a string.

Now we are going to replace using the below methods

  1. Javascript replaceAll() method
  2. Javascript replace with regex global method

Let’s start today tutorial How to replace all occurrences of a string in JavaScript?

Javascript replaceAll() method

JavaScript replaceAll() method provides for replacing the same strings in your string data. but it’s available only in new updated modern browsers.

it also does not work in older node.js versions.

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replaceAll('dog', 'monkey'));

In the above example, we are replacing all occurrences of dog to monkey check below output.

replaceAll, Javascript, Example

Javascript replace with regex global method

JavaScript replace() method plus regex global method we can also replace all occurrences of the same string.

it’s older way i.e it supports all places.

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace(/dog/g, 'monkey'));

In the above code, we are replacing dog globally from string with monkey check below output.

replace, regex, Javascript, Example