This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
65. add comma to number
Solution: We can first convert the number to a string and then insert commas after every three digits from the right using a regular expression.
Here's the code:
function addComma(num) { // convert number to string const str = num.toString(); // use regex to add commas return str.replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');}
Explanation:
- We first convert the number to a string using
toString()
. - Then we use the
replace()
method of the string to search for groups of three digits from the right using a regular expression. The regular expression matches any digit (\d
) that is followed by one or more groups of three digits (\d{3}
) and is not followed by any more digits ((?!\d)
). Theg
flag at the end tells thereplace()
method to replace all occurrences, not just the first one. - Inside the
replace()
method, the replacement string'$1,'
adds a comma after each matched digit. Here,$1
represents the first group of the matched string, which is a single digit.
Finally, we return the modified string containing commas as thousand separators.