Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Begana Choi
PLUS
Begana Choi
Courses Plus Student 13,124 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

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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Trevor Maltbie
Full Stack JavaScript Techdegree Graduate 17,005 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?