Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript replace all comma in a string

I want to convert all comma in below string to space or say blank, i tried below code which is only taking care of first comma, I tried global indicator /g as well but that do nothing.

What I am doing wrong?

var str="D'Or, Megan#LastName Jr., FirstName#BMW, somename#What, new";
str=str.replace(',','');
alert(str)

Output

D'Or Megan#LastName Jr., FirstName#BMW, somename#What, new

expected

D'Or Megan#LastName Jr. FirstName#BMW somename#What new

like image 863
Dev G Avatar asked Mar 03 '14 11:03

Dev G


1 Answers

To replace any given string u need to use regular expressions. You need to use a RegExp Object to ensure crossbrowser compatibility.

The use of the flags parameter in the String.replace method is non-standard. For cross-browser compatibility, use a RegExp object with corresponding flags.

//Init
var str = "D'Or, Megan#LastName Jr., FirstName#BMW, somename#What, new";
var regex = new RegExp(',', 'g');

//replace via regex
str = str.replace(regex, '');

//output check
console.log(str); // D'Or Megan#LastName Jr. FirstName#BMW somename#What new

See that fiddle: http://jsfiddle.net/m1yhwL3n/1/ example. Thats how it will work fine for all browsers.

like image 107
lin Avatar answered Sep 27 '22 21:09

lin