Regular Expression for formatting numbers in JavaScript

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

    This can be done in a single regex, no iteration required. If your browser supports ECMAScript 2018, you could simply use lookaround and just insert commas at the right places:

    Search for (?<=\d)(?=(\d\d\d)+(?!\d)) and replace all with ,

    In older versions, JavaScript doesn't support lookbehind, so that doesn't work. Fortunately, we only need to change a little bit:

    Search for (\d)(?=(\d\d\d)+(?!\d)) and replace all with \1,

    So, in JavaScript, that would look like:

    result = subject.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    

    Explanation: Assert that from the current position in the string onwards, it is possible to match digits in multiples of three, and that there is a digit left of the current position.

    This will also work with decimals (123456.78) as long as there aren't too many digits "to the right of the dot" (otherwise you get 123,456.789,012).

    You can also define it in a Number prototype, as follows:

    Number.prototype.format = function(){
       return this.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
    };
    

    And then using it like this:

    var num = 1234;
    alert(num.format());
    

    Credit: Jeffrey Friedl, Mastering Regular Expressions, 3rd. edition, p. 66-67

提交回复
热议问题