I have built a function that formats a number using commas, similar to what the toLocaleString
method does. To achieve that, I used a regular expression and recursion. However, I have a feeling that this could've been done better.
I did some research but was not able to find the answer I'm looking for. So, my question is...Is there a better way to do this?
function transform(value) {
const pureNumber = parseInt(value);
const numberParts = [];
function format(val) {
let formatted = val.toString().split(/(\d{3})$/).filter(i => !!i).join(",");
const splitted = formatted.split(",");
if(splitted.length > 1){
numberParts.unshift(splitted[1]);
return format(splitted[0]);
}
numberParts.unshift(splitted[0]);
return numberParts.join(",");
}
return format(pureNumber.toString());
}
const data = "1234567890";
const result = transform(data);
console.log(result);
What I need you to note is that I used a regular expression to split the string, however, I was wondering if there is a way to only use regular expressions to avoid the recursion? I.e., Is there a way to use the regular expression starting at the end of the string and repeating towards left?