Get the fundamentals down and the level of everything you do will rise. - Michael Jordan
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:
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.
- 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.