当前位置:网站首页>JS regular expression to implement the thousands separator

JS regular expression to implement the thousands separator

2022-06-22 05:15:00 Lanting ancient ink

function numberThousands (number, thousandsSeperator = ',') {
    
  return String(number).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousandsSeperator)
}

explain

First of all, understand : Positive positive preview (look ahead positive assert) and Positive negative pre check (negative assert)

Positive positive preview (look ahead positive assert):

In any match pattern Match at the beginning of the string to find the string . This is a non fetch match , in other words , The match does not need to be retrieved for later use . for example ,“Windows(?=95|98|NT|2000)“ Can match "Windows2000" Medium "Windows”, But can't match "Windows3.1" Medium "Windows”. Pre check does not consume characters , in other words , After a match happens , Start the search for the next match immediately after the last match , Instead of starting after the character that contains the prefetch .

Positive negative pre check (negative assert):

In any mismatch pattern Match at the beginning of the string to find the string . This is a non fetch match , in other words , The match does not need to be retrieved for later use . for example "Windows(?!95|98|NT|2000)“ Can match "Windows3.1" Medium "Windows”, But can't match "Windows2000" Medium "Windows". Pre check does not consume characters , in other words , After a match happens , Start the search for the next match immediately after the last match , Instead of starting after the character that contains the prefetch .

/(\d)(?=(\d\d\d)+(?!\d))/g Regular expression diagram :

 Insert picture description here
Assuming a string 12345, Regular expressions (\d)(?=(\d\d\d)+) First , matching 1, Find out 1 In the back 234, The forward preview has found , therefore 1 Will be matched to ; Back again , matching 2 , Find out 345, therefore 2 Also matched to , Here's the picture

 Insert picture description here
add (?!\d), Also make sure that the last string of the forward look-up It can't be numbers

原网站

版权声明
本文为[Lanting ancient ink]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220512230490.html