420

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
  • 21,441
  • 28
  • 74
  • 95
  • 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

880

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

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

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

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an 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).

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

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

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

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

console.log( newStr );  // "this-is-a-test"
VisioN
  • 138,460
  • 30
  • 271
  • 271
  • 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
  • cool, it works in my case. thanks! – Troyan Victor Apr 28 '22 at 17:02
183

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);
RobG
  • 134,457
  • 30
  • 163
  • 204
  • 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... – CSchwarz 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 is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
  • 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 is supporting Monica 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