In Javascript, we have .Replace() method to replace a sub-string from a string, but what if we have more than 1 occurence of a sub-string which we want to replace, so in this article, I have mentioned how we can Replace all occurrences in string using Javascript using various examples.

Using ReplaceAll()

This method is now supported by all modern browsers, including Microsoft Edge, the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith value.

const p = 'Hello, Vikram here, Vikram likes to code in Javascript';

console.log(p.replaceAll('Vikram', 'Vikas'));
//output: Hello, Vikas here, Vikas likes to code in Javascript

replace-all-occurences-in-string-javascript

Using Regular Expressions(Regex) with Replace()

One of the easiest way to replace all occurences of a sub-string from a string is to use Regex with .Replace Method().

If the above method, replaceAll doesn't work for you or you want to create a custom function to support old browsers, then you can create a custom method with .Replace() and Regex as shown below

const p = 'Hello, Vikram here, Vikram likes to code in Javascript';

String.prototype.replaceAllNew = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};
console.log(p.replaceAllNew('Vikram', 'Vikas'));
//output: Hello, Vikas here, Vikas likes to code in Javascript

In Order to make replace() method, replace all occurrences of the pattern you have to enable the global flag on the regular expression

So, you will need to Append g after at the end of regular expression literal: '/search/g'

OR, when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g'), we are using this way in above example.

Using Split and Join

If none of the above methods works for you, then you can simply use .Split() and .Join() methods.

In this approach, we will Split String which we want to remove and then we will use Join() method using replaced string.

So it would look like below

const splittedString = string.split(search);

then

const resultString = splittedString.join(replaceWith);

For example, if we want to replace all "," with " " in a string "Hello,World,Vikas Here", then code would be as below

const search = ',';
const replaceWith = ' ';

const result = 'Hello,World,Vikas Here'.split(search).join(replaceWith);

console.log(result);

//output
//Hello World Vikas Here

So, these are some of the methods, using which you can replace all occurences of string in Javascript.

You may also like to read:

Replace All Spaces in Javascript

Filter Array With Multiple Values in Javascript

Top Best React Component libraries

Get enum key by value in Typescript

Change Text color on click using Javascript

Read XML using Javascript

What is JQuery IsNumeric like function in Javascript?

Password and Confirm password validation using Javascript