如何在范围上分割字符串 [英] How to split a string on range
本文介绍了如何在范围上分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新来的朋友,我需要您的帮助。
谁能帮助我如何将这段代码行形式的JavaScript编写到Flutter:
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);
}
我看到了。 splitMapJoin,但我做不到。
I saw something with .splitMapJoin, but I couldn't do it.
推荐答案
尝试 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
在问题编辑后更新
您是否需要这样的东西?
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
这篇关于如何在范围上分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文