• Post category:JavaScript
  • Reading time:2 mins read

In this article, we will show you how to replace multiple strings in JavaScript. Here, we show you the simplest way to replace all occurrences of a string via a single line of code.

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 single method (Using regular expression) in this article.

Replace all instances of string using 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;
}

I hope you find this article helpful.

Leave a Reply