Enhancing regex of thousands separator?

后端 未结 5 1231
长发绾君心
长发绾君心 2021-01-15 03:50

I saw this beautiful script to add thousands separator to js numbers:

function thousandSeparator(n, sep)
{
    var sRegExp = new RegExp(\'(-?[0-9]+)([0-9]{3         


        
5条回答
  •  甜味超标
    2021-01-15 04:01

    Here is an ugly script to contrast your beautiful script.

    10000000.0001 .toString().split('').reverse().join('')
    .replace(/(\d{3}(?!.*\.|$))/g, '$1,').split('').reverse().join('')
    

    Since we don't have lookbehinds, we can cheat by reversing the string and using lookaheads instead.

    Here it is again in a more palatable form.

    function thousandSeparator(n, sep) {
    
        function reverse(text) {
            return text.split('').reverse().join('');
        }
    
        var rx = /(\d{3}(?!.*\.|$))/g;
    
        if (!sep) {
            sep = ',';
        }
    
        return reverse(reverse(n.toString()).replace(rx, '$1' + sep));
    
    }
    

提交回复
热议问题