Reputation: 1407
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)
D'Or Megan#LastName Jr., FirstName#BMW, somename#What, new
D'Or Megan#LastName Jr. FirstName#BMW somename#What new
Upvotes: 5
Views: 27039
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
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
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
Reputation: 15387
Try this
var str="D'Or, Megan#LastName Jr., FirstName#BMW, somename#What, new";
str=str.replace(/,/g ,'');
alert(str)
Upvotes: 1
Reputation: 958
You need to use the global option in the following way:
str=str.replace(/,/g,'');
Upvotes: 3