Replace all occurrences of a string in JavaScript

Today we will show you how to replace all occurrences of a string in JavaScript. Here we show you the simplest way to replace all instances of string via a single line of code.

How to replace all occurrences of a string in JavaScript, javascript replace all spaces, string replace in javascript, javascript string replace multiple, How to replace all dots in a string using JavaScript.

Checkout our previous articles on React JS

Javascript replace() method replaces only the first occurrence of the string. There are several methods are available to replace all occurrences of a string in JavaScript. But we will discuss only two methods in this article.

Demo & Source Code

Github Repository

Way to Replace all occurrences of a string in JavaScript

  1. JavaScript string replace method with regular expression
  2. JavaScript split and join method

1. JavaScript string replace method with regular expression

Here we have to use regular expressions to replace all words or string via a single line. We will use g flag (global) instead of normal string character as a regular expression.

Below is a small example where we will replace “” instead of “is”.

Now if you want to replace the case insensitive string then you have to use gi flag. Checkout the below example.

2. JavaScript split and join method

Another simplest way to replace all is to use Split and Join method.

3. Output

Output - Replace all occurrences of a string in JavaScript - Clue Mediator
Output – Replace all occurrences of a string in JavaScript – Clue Mediator
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *