问题
I new in flutter, and i need your help for something. Can anyone help me how can i write this code line form JavaScript to Flutter:
onInputChange(event, backspace) {
let newVal = event.replace(/\D/g, '');
if (backspace && newVal.length <= 6) {
newVal = newVal.substring(0, newVal.length - 1);
}
if (newVal.length === 0) {
newVal = '';
} else if (newVal.length <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, '($1)');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) $2');
} else if (newVal.length <= 10) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
} else {
newVal = newVal.substring(0, 10);
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
}
this.ngControl.valueAccessor.writeValue(newVal);
}
I saw something with .splitMapJoin, but I couldn't do it.
回答1:
try replaceFirstMapped
var value = '1234567890';
var regExp = RegExp(r'^(\d{0,3})(\d{0,3})(\d{0,4})');
var phoneNumber = value.replaceFirstMapped(regExp, (match) {
return '(${match.group(1)}) ${match.group(2)}-${match.group(3)}';
});
print(phoneNumber); //(123) 456-7890
update after the question edit
Do you need something like this:
format(String value) {
var regExp2 = RegExp(r'^(\d{0,3})(\d{0,3})(\d{0,4})');
return value.replaceFirstMapped(regExp2, (match) {
var res = '';
if (match.group(1).isNotEmpty) {
res += '(${match.group(1)})';
}
if (match.group(2).isNotEmpty) {
res += ' ${match.group(2)}';
}
if (match.group(3).isNotEmpty) {
res += '-${match.group(3)}';
}
return res;
});
}
var value = '1234567890';
var value2 = '12345';
print(format(value)); //(123) 456-7890
print(format(value2)); //(123) 45
来源:https://stackoverflow.com/questions/62191872/how-to-split-a-string-on-range