Issue
I'm using the following jQuery plug-in to automatically add commas to a number. The problem is, when a decimal amount (like $1,000.00) is entered, it's changing it to $1,000,.00.
How can the regex be updated to ignore the decimal point and any characters after it?
String.prototype.commas = function() {
return this.replace(/(.)(?=(.{3})+$)/g,"$1,");
};
$.fn.insertCommas = function () {
return this.each(function () {
var $this = $(this);
$this.val($this.val().replace(/(,| )/g,'').commas());
});
};
Solution
seems like a simple fix. Just change the .{3}
(any three characters) to [^.]{3}
(any non-period three characters)
String.prototype.commas = function() {
return this.replace(/(.)(?=([^.]{3})+$)/g,"$1,");
};
EDIT:
or better yet:
String.prototype.commas = function() {
return this.replace(/(\d)(?=([^.]{3})+($|[.]))/g,"$1,");
};
Answered By - Joseph Marikle Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.