Any chance someone might be able to help me out with understanding this block of code? One of my small projects I am trying to add commas for numbers within the thousands… so 1200 would equall 1,200. I did some reading on MDN and stack overflow and came up with this function
function convert(num) {
num= num.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(num))
num = num.replace(pattern, "$1,$2");
return num;
}
While it does work, I am definitely having a hard time understanding it, especially the variable pattern. If anyone wouldn’t mind helping me understand it, I’d really appreciate it
Commas have no meaning with numerical types and so you wouldn’t possibly run into an issue where you’d need to do that.
It makes sense to think about how you would convert the number 10000000 on paper. You’d probably want to start on the very right, adding commas every 3 digits until you have no more numbers to group.
10000000
10000,000
10,000,000
This is how the regex pattern works as well. The while loop continuously tests the string num. It’s looking for a group of three digits with numbers to the left. Commas will invalidate the pattern.
1000 - valid 100 - invalid, only three digits 10000,000 - valid, the substring 10000 matches 100,0 - invalid, the comma isn’t specified in the regex pattern.
num.replace() is doing exactly what it says, replacing the values it finds based on the pattern. Regex allows you to group results with parentheses and then reference them with $N, where N is the nth result in the pattern.
/($1)($2)($3)...($N)/
replace() returns the new string, so each time we call it, we want to assign that result back to num. Hence,
You start with a number, so returning a number would be a no-op. Remember, commas do not exist in numbers. They have no numerical value. They exist only to help humans read large values, so anything with a comma will be a string.