Clue Mediator

Replace all occurrences of a string in JavaScript

πŸ“…October 17, 2019
πŸ—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”.

function handleReplaceAll() {
  var sentence = 'This is test example and it Is easy to learn.';
  var output = sentence.replace(/is/g, '-'); // Output: Th- - test example and it Is easy to learn.
  document.getElementById("demo").innerHTML = output;
}

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

function handleReplaceAllCI() {
  var sentence = 'This is test example and it Is easy to learn.';
  var output = sentence.replace(/is/gi, '-'); // Output: Th- - test example and it - easy to learn.
  document.getElementById("demo1").innerHTML = output;
}

2. JavaScript split and join method

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

function handleReplaceAllSplitJoin() {
  var sentence = 'This is test example and it Is easy to learn.';
  var output = sentence.split('is').join('-'); // Output: Th- - test example and it Is easy to learn.
  document.getElementById("demo2").innerHTML = output;
}

3. Output

Output - Replace all occurrences of a string in JavaScript - Clue Mediator

Output - Replace all occurrences of a string in JavaScript - Clue Mediator