Regular Expression for formatting numbers in JavaScript

前端 未结 14 1497
遥遥无期
遥遥无期 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:15

    First reverse a character array, then add commas after every third number unless it's just before the end of the string or before a - sign. Then reverse the character array again and make it a string again.

    function add_commas(numStr){
        return numStr.split('').reverse().join('').replace(/(\d{3})(?=[^$|^-])/g, "$1,").split('').reverse().join('');
    }
    

提交回复
热议问题