4
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’ve been analyzing it for a long time and I still don’t 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 for 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 digit 1 as a match if it is not followed by 3 digits and a comma, just like the regex. You wouldn’t have to take the digit 0?
Because the character "?" indicates an optional match that may or may not be there
– Sorack
You took the
g
in both examples... it was right mistake?– Sergio
In the regex documentation of Mozilla, it says that this is a "Lookahead", and that in this case x(?=y), x only matches if it is followed by y, so it would not be optional.
– Johnny Gabriel
yes Sergio, I accidentally removed :b
– Johnny Gabriel
The link to the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions. That’s why I’m not sure how this regex works
– Johnny Gabriel