JavaScript String – replace() Method

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a Regular Express, and the replacement can be a string or a function to be called for each match.

Replace first occurrence of character
var str = “hello,,”;
str = str.replace(‘,’, “|”);
Output: hello|,

Replace all occurance of character. In example below we will replacing , comma with | pipe
var myStr = “hello,,world”;
myStr = myStr.replace(/,/g, “|”);
Output: hello||world,

In the above example, we used the global (g) flag on the regular expression literal to match all occurrences. The i flag is also often useful for a case-insensitive match.

Replace last occurrence of character. In this case we will be replacing last , comma character with | pipe.
var str = ‘Hello,,world’;
str = str.replace(/,([^,]*)$/, ‘|’+’$1’);
Output: hello,|world,