Navigate back to the homepage

How to replace all occurrences of a string in JavaScript?

Infinitbility
JavaScript
November 1st, 2021 · 1 min read
How to replace all occurrences of a string in JavaScript?

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.

1const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
2
3console.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.

1const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
2
3console.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

Join our email list and get notified about new content

No worries, I respect your privacy and I will never abuse your email.

Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo

Tutorials

Categories

More articles from Infinitbility

How to use regex in typescript?

How to use regex in typescript?

Example of regex in typescript

October 31st, 2021 · 1 min read
How to check type of variable in typescript?

How to check type of variable in typescript?

Example of check datatype of variable in typescript

October 29th, 2021 · 1 min read
© 2020–2021 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]