427

I have a string with multiple commas, and the string replace method will only change the first one:

var mystring = "this,is,a,test"
mystring.replace(",","newchar", -1)

Result: "thisnewcharis,a,test"

The documentation indicates that the default replaces all, and that "-1" also indicates to replace all, but it is unsuccessful. Any thoughts?

017Bluefield
  • 161
  • 2
  • 13
mike
  • 22,931
  • 31
  • 77
  • 100
  • 2
    What documentation? The standard - http://es5.github.com/#x15.5.4.11 - does not define a third parameter, and MDN - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace - defines a non-standard third parameter as a string representing flags, not an integer... – Šime Vidas May 16 '12 at 00:01

3 Answers3

897

The third parameter of the String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it. It was eventually removed and replaced with String.prototype.replaceAll() (see below).


Modern solution (2022)

Use String.prototype.replaceAll(). It is now supported in all browsers and NodeJS.

var myStr = "this,is,a,test";
var newStr = myStr.replaceAll(",", "-");

console.log( newStr );  // "this-is-a-test"

The old way is to use a regular expression with g (global) flag

var myStr = "this,is,a,test";
var newStr = myStr.replace(/,/g, "-");

console.log( newStr );  // "this-is-a-test"
Have issues with regular expressions?

It is important to note, that regular expressions use special characters that need to be escaped. For example, if you need to escape a dot (.) character, you should use /\./ literal, as in the regex syntax a dot matches any single character (except line terminators).

If you need to pass a variable as a replacement string, instead of using regex literal you may create a RegExp object and pass a string as its first argument. The usual escape rules (preceding special characters with \ when included in a string) will be necessary.

function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}

var myStr = "this.is.a.test";
var reStr = escapeRegex(".");
var newStr = myStr.replace(new RegExp(reStr, "g"), "-");

console.log( newStr );  // "this-is-a-test"
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • 3
    Excellent answer. /g makes global search of comma and replacing it in entire string.It works this way, Am I correct?? – Ravi Shankar Kota Mar 17 '15 at 13:01
  • Can you please describe in details regarding /"Seprator"/g – MSTdev Nov 05 '15 at 07:49
  • 1
    @MSTdev This is a typical *regular expression* with `g` flag (a.k.a. *"global search"*). The algorithm is simple: regular expression finds ALL matches (here commas) in the given string. More information about regular expressions in JavaScript you can find in [**MDN**](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Advanced_searching_with_flags). – VisioN Nov 05 '15 at 08:37
  • 1
    Not working in TypeScript. – ahmadalibaloch Apr 16 '17 at 07:05
  • What if i need to replace "\" ? – chows2603 Aug 25 '17 at 17:18
  • 3
    @chows2603 use `/\\/g` and it will work. – VisioN Sep 06 '17 at 19:17
  • What about if I want to remove all / from my string? – Anna Nov 28 '17 at 08:42
  • @Anna nothing special, just escape it as well: `/\//g`. – VisioN Nov 28 '17 at 09:08
  • Have an upvote. And a slight tweak for more elegant display if your target is text rather than data: var newStr = myStr.replace(/,/g, ' -'); [The space in front of the hyphen centers it in the 3 spaces between words which normally result from a comma's placement adjacent to a word, followed by a space and a new word. – brianfit Dec 26 '19 at 13:45
184

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);
RobG
  • 142,382
  • 31
  • 172
  • 209
  • 2
    This works w/o Regex, globaly, with variables and special characters (ex: '['+variable+']'). Genius. – Aureliano Far Suau Aug 22 '14 at 17:48
  • 1
    it's a good answer, I tested the `replace` function with dots '.' but it doesn't work as expected, but you answer made it good – Sredny M Casanova Mar 18 '16 at 17:17
  • 4
    @SrednyMCasanova that is because in regex, the period is a special character, and you should escape it with `\.` Example: `var mystring = "this.,.is.,.a.,.test"; mystring.replace(/\./g , "|");` See [MDN RegExp - Special characters meaning in regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Special_characters_meaning_in_regular_expressions) – julian soro Aug 01 '16 at 23:21
  • 3
    is it slower/faster than regex with /g? – tomalone Mar 14 '19 at 12:25
  • Note a semicolon is missing from the second line above (var newchar) I tried to make an edit but stackoverflow said I couldn't... – Schwarz Software Oct 09 '19 at 03:18
  • 1
    @CSchwarz - I was about to make the edit for you but then remembered that many [JS semicolons are optional](https://news.codecademy.com/your-guide-to-semicolons-in-javascript) including these. Many developers very [adamantly insist](https://stackoverflow.com/q/444080/8112776) on including them anyway. While I have no qualms about editing answers if I'm 100% sure (exception: took me 2 days to muster courage to edit one of [Atwood](//stackoverflow.com/users/1)'s answers, lol), but in this case I'll leave it as-is. You'll be [able to edit](//stackoverflow.com/help/privileges/edit) at 2000 rep. – ashleedawg Nov 17 '19 at 11:14
51
var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • not working for var mystring = "this,is.a.test" mystring.replace(/./g, ">"); It replace the whole string – Dinesh Jain Oct 24 '17 at 13:29
  • 2
    @DineshJain In regex dot (`.`) has a special meaning, it means every char, and like all other special chars, needs to be escaped with `\` if you want to use their value "literally". if you want to replace only dots you need to use `\.`. – gdoron Oct 24 '17 at 13:54
  • I added the String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); }; solves my problem @gdoron Thanks – Dinesh Jain Oct 25 '17 at 05:12