Reputation: 7969
I am using prototype method to replace comma in string but the function giving same string
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
Upvotes: 0
Views: 79
Reputation: 25672
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
Works just fine. I guess you're expecting the following effect:
var str = 'foo,bar,baz';
str.removeLastComma();
console.log(str); //foo.bar.baz
Unfortunately, this is not possible because the strings in JavaScript are immutable.
Try this instead:
var str = 'foo,bar,baz';
str = str.removeLastComma();
console.log(str); //foo.bar.baz
NOTE: better call your method "removeCommas" or something like that. Remove last comma means that you're going to remove only the last one.
For removing the last comma you can use the following regular expression:
String.prototype.removeLastComma = function(){
return this.replace(/,(?=[^,]*$)/, '.');
}
Upvotes: 2
Reputation: 958
it works fine for me. For a sample implementation see: http://jsfiddle.net/9Hrzp/
String.prototype.removeLastComma = function(){
return this.replace(/,/g, '.');
}
alert("foo,bar".removeLastComma());
Upvotes: 0