[JavaScript] 每三位数字加逗号

// 1,234,567,890
'1234567890'.replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,');

注:
(1)(?:x)
Matches 'x' but does not remember the match. The parentheses are called non-capturing parentheses, and let you define subexpressions for regular expression operators to work with. Consider the sample expression /(?:foo){1,2}/. If the expression was /foo{1,2}/, the {1,2} characters would apply only to the last 'o' in 'foo'. With the non-capturing parentheses, the {1,2} applies to the entire word 'foo'.

(2)x(?=y)
Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead. For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.

(3)x(?!y)
Matches 'x' only if 'x' is not followed by 'y'. This is called a negated lookahead. For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point. The regular expression /\d+(?!\.)/.exec("3.141") matches '141' but not '3.141'.


参考

Regular Expressions - MDN

你可能感兴趣的:([JavaScript] 每三位数字加逗号)