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.
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
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);
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