PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to update this jQuery plug-in/regex to ignore decimals when adding commas?

 August 07, 2022     decimal, jquery, jquery-plugins, regex     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing