Dev G
Dev G

Reputation: 1407

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

Upvotes: 5

Views: 27039

Answers (5)

lin
lin

Reputation: 18392

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.

Upvotes: 4

Dev G
Dev G

Reputation: 1407

My Bad i was using comma for regex

wrong str=str.replace('/,/g','');

good str=str.replace(/,/g,'');

Thanks all for correct this..I will add points for all of you. :)

Upvotes: -1

Vinod VT
Vinod VT

Reputation: 7149

Try this code,

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

Upvotes: 2

Amit
Amit

Reputation: 15387

Try this

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

DEMO

Upvotes: 1

athms
athms

Reputation: 958

You need to use the global option in the following way:

str=str.replace(/,/g,'');

Upvotes: 3

Related Questions