Regular Expression for formatting numbers in JavaScript

前端 未结 14 1478
遥遥无期
遥遥无期 2020-11-30 19:35

I need to display a formatted number on a web page using JavaScript. I want to format it so that there are commas in the right places. How would I do this with a regular exp

14条回答
  •  遥遥无期
    2020-11-30 20:08

    Brandon,

    I didn't see too many answers working the regex from the decimal point back, so I thought I might chime in.

    I wondered if there is any elegant benefit to re-writing the regexp to scan from the back forward...

    function addCommas(inputText) {
        // pattern works from right to left
        var commaPattern = /(\d+)(\d{3})(\.\d*)*$/;
        var callback = function (match, p1, p2, p3) {
            return p1.replace(commaPattern, callback) + ',' + p2 + (p3 || '');
        };
        return inputText.replace(commaPattern, callback);
    }
    

    >> Fiddle Demo <<

    This accounts for any decimal place.

提交回复
热议问题