How to Replace All Occurrences of a String in JavaScript

In this short tip post, we will learn how to replace all occurrence of a string in JavaScript.

Objective

Finding the occurrences of a given string and replacing them with the given word.

Approach

There are two approaches:

  1. Using RegEx
  2. Using JavaScript Split() and Join() method

Code

We can use Regular expression to this task. Here is the code.

var phrase = 'Bullet train are the best. They are among the best Train in the world.'
var newPhrase = phrase.replace(/train/g, 'trains')

console.log(newPhrase);
//Output: Bullet trains are the best. They are among the best Train in the world.

This is case sensitive RegEx. That means, Trains and train is different word.

Here is the case insensitive code.

var phrase = 'Bullet train are the best. They are among the best Train in the world.'
var newPhrase = phrase.replace(/train/gi, 'trains')
console.log(newPhrase);
//Output: Bullet trains are the best. They are among the best trains in the world.

Another approach is using split() and join() method.

var newPhrase2 = phrase.split('train').join('trains');
console.log(newPhrase2);

Here string is first split by the matching word and later we append the string with the replacement word using join() method. This is case sensitive.

Check out the codepen for the live demo.

See the Pen
replace string javascript
by Shahid Shaikh (@codeforgeek)
on CodePen.

Love JavaScript? Learn more about it here.

Pankaj Kumar
Pankaj Kumar
Articles: 209