I'm trying to translate a js function to 'commify' numbers to Dart and I'm getting hung up on the regex.
The function takes a number like 1234.56 and inserts commas as separators: 1,234.56
The js function looks like:
addCommas : function(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
I've converted most of it but I'm hung up on the rgx.test(x1) and x1.replace lines.
I think rgx.text(x1) should be x1.contains(rgx) in Dart. I haven't been able to figure out how to get the matching substrings ($1 and $2) in Dart.
Here's my Dart
test program. The $1,$2 in the replaceAll prevent the program from compiling.
main(){
var input = '1234.56';
final matcher = new RegExp(r'^(\d+)(\d{3})$');
List input_parts = input.split('.');
String first_part = input_parts[0];
String second_part = first_part.length > 1 ? ".${input_parts[1]}" : '';
while ((first_part).contains(matcher)) {
first_part = first_part.replaceAll(matcher, '$1,$2');
}
return '$first_part$second_part';
}
Any ideas? Thanks!