Get the fundamentals down and the level of everything you do will rise. - Michael Jordan
As stated in my original post, I do at least 1 hour of video lessons from Watch and Code every day. If you're interested in learning Javascript in a way that goes beyond basic tutorials and gives you a foundational, practical knowledge without relying on frameworks - I'd highly recommend it. If you're reading these posts, please keep in mind that these are just my notes, and I'm not an expert (yet!). If your goal is also to master the fundamentals of Javascript, please head over to Watch and Code and start your journey there!
All screenshots were annotated using Shotty.
Today we're inspecting the unformat method in Accounting JS.
It lets you pass in a string and an optional decimal separator and will clean out any formatting (currency symbols, whitespace, thousands separators, etc.) and will return a number.
Let's look at the source code:
First we use recursion to unformat arrays:
Next up is a different way of creating regular expressions that is slightly harder to work with, but more powerful.
The pattern is written as a string combined with a variable.
If we evaluate this with the default decimal character (.), then we get something that looks very close to one of our old regular expressions:
Let's save these to variables and prove that they're the same.
So why would you choose the constructor way of doing this? Well you get to use variables, so you can dynamically construct the pattern.
We can see this expression in RegExr to illustrate:
So that's what this line does:
Moving on.
unformatted is set to the return value of parseFloat. To figure out what we're passing into parseFloat, we need to take a look at these lines:
It does a bunch of replaces of the string to unformat it, and then puts it through parseFloat to turn it to a string and keep the decimals.
"If the unformatted is not a number, then set it equal to zero. If it is a number, then just return in.
Summary
- Use regular expression constructors to dynamically use variables in our regular expressions.
- Chain together several .replace methods to strip out cruft.
- Return a nice clean number.