Add commas or spaces to group every three digits

前端 未结 9 1731
日久生厌
日久生厌 2020-11-27 15:50

I have a function to add commas to numbers:

function commafy( num ) {
  num.toString().replace( /\\B(?=(?:\\d{3})+)$/g, \",\" );
}

Unfortun

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 16:09

    Assuming your usage examples are not representative of already-working code but instead desired behavior, and you are looking for help with the algorithm, I think you are already on the right track with splitting on any decimals.

    Once split, apply the existing regex to the left side, a similiar regex adding the spaces instead of commas to the right, and then rejoin the the two into a single string before returning.

    Unless, of course, there are other considerations or I have misunderstood your question.

提交回复
热议问题