-2

Why if i print an array (converted to a string) the .replace function works only on the first ,?

var messages = ["a", "b", "c"];

alert(messages.toString().replace(',',''));
Eugenios
  • 11
  • 5

3 Answers3

3

That is how .replace() works, it only replaces the first match.

To replace all matches, simply use regex

.replace(/,/g, '') the g means global, and tells replace to look for ALL matches. The / are regex syntax. Learn more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Robbie Milejczak
  • 5,664
  • 3
  • 32
  • 65
0

If you want to replace all the occurance, you have to use the global replace

/,/g 

So

alert(messages.toString().replace( /,/g,''));

https://jsfiddle.net/mn93pxth/1/

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 91k rep and you don't know that you shouldn't post code examples to 3rd party sites instead of just putting a code snippet into your answer? – Scott Marcus Nov 09 '17 at 16:44
0

Because that's what passing a string to replace does. Using a regular expression with the global g flag solves it.

var messages = ["a", "b", "c"];

alert(messages.toString().replace(/,+/g,''));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71