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(',',''));
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(',',''));
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
If you want to replace all the occurance, you have to use the global replace
/,/g
So
alert(messages.toString().replace( /,/g,''));
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,''));