0

I tried to turn number like "123456" into "123,456". My original code is

number.replace(/(?=(?:\d{3})+(?!\d))/g,',')

It works fine when the size of number isn't a multiple of three.

So I tried to add (?<=\d) to make sure the comma wouldn't be added at the begin.But chrome said it's a invalid regular expression

number.replace(/(?=(?<=\d)(?:\d{3})+(?!\d))/g,',')

So what is the correct expression to format the number?

UPDATE :

Solved the comma's issue.

But still I don't understand why the expression would throw error.Those brackets are paired.

var number = "123456"; number = number.replace(/(?=(?<=\d)(?:\d{3})+(?!\d))/g,',') `

KyleCTX
  • 41
  • 9

1 Answers1

0
n.toFixed(2).replace(/./g, function(c, i, a) {
    return i && c !== "." && ((a.length - i) % 3 === 0) ? ',' + c : c;
});

Reference: How can I format numbers as money in JavaScript?

Community
  • 1
  • 1
amit kate
  • 120
  • 3