How does this regex work in js?

3

I found on the internet this regex in javascript that formats monetary values in R $:

Number( 1450999 )
.toFixed( 2 )
.replace( '.', ',' )
.replace( /(\d)(?=(\d{3})+,)/g, "$1," )
// 1450999 -> 1.450.999,00

I have been analyzing for a long time and I still do not understand how this regex works. For example, in the case regex does a global search, but if I remove this parameter, the return is a match to the digit 1:

Number( 1450999 )
.toFixed( 2 )
.replace( '.', ',' )
.replace( /(\d)(?=(\d{3})+,)/, "$1." )
// 1450999 -> 1.450999,00

The question is as follows, how can this regex take the digit 1 as a match if it is not followed by 3 digits and a comma, just as it sends the regex. Would not you have to get the digit 0?

    
asked by anonymous 03.11.2016 / 17:29

1 answer

3

When you have .replace(/(\d)(?=(\d{3})+,)/g, "$1.") what happens is the following:

The Number(1450999).toFixed(2).replace('.', ',') line transforms your number into a string like this: "1450999,00" . And it's about this string that regex acts:

  • (\d) creates a catch-only group with numbers
  • (?=(\d{3})) indicates that the catch group defined above should search for (\d{3})
  • (\d{3})+ creates a group of number captures, grouped 3 to 3, one or more times ( + )
  • , indicates that after the catches all come a comma in the string
  • g indicates that you should continue searching after you have found a match

Then replace replace each group of 3 numbers by these 3 numbers but adding a dot.

There is a great website for analyzing regular expressions. In your case it would look like this: link

    
03.11.2016 / 17:36