JavaScript Regular Expressions in JavaScript Reformatting User Input Using Replace with Captured Groups

Begana Choi
Begana Choi
Courses Plus Student 13,122 Points

why do we use /(\d*)(\d{2})/ instead of /(\d{2})(\d{2})/ in this video?

in this video in regex variable /(\d*)(\d{2})/

but why not /(\d{2})(\d{2})/ or /(\d+)(\d{2})/ ??

we already know what is inside of sting and we could use those 2 for regular expression.

1 Answer

Ryan Groom
Ryan Groom
18,597 Points

Begana Choi They are setting up the Regular expression so that it will replace any numeric value "5337" and turn it into a monetary value "$53.37". Since monetary values have a 2 digit decimal value for the change ($0.37) the second capture group is "(\d{2})". This grabs the last two digit values that way they can be separated from the digits in front of them. The amount of digits before the decimal point could vary though. Instead of $53.37 you could have $153.37. So in an instance like this, for your first capture group you wouldn't want to only grab two digits, because it could be any amount. So this is why they use (\d*). The * symbol represents 0 or more of the preceding character. Therefore they can grab any amount of digits before the final two digits and set them on the left side of the decimal point.

I hope this makes sense! Let me know.

Trevor Maltbie
.a{fill-rule:evenodd;}techdegree seal-36
Trevor Maltbie
Full Stack JavaScript Techdegree Graduate 16,984 Points

Even though the regex is set for \d* allowing for any number of digits, in this practice it knows to only print 2 numbers before the . because the following part of the regex requires 2 more digits. 5337 only has 4. The regex knows to save 2 digits for the final part?