繁体   English   中英

国际美国电话号码掩码

[英]International US phone number mask

我正在使用 react-native-material-textfield 并且需要一个解决方案来在用户输入时实时格式化美国号码:例如从“0000000000”到“+1 (000) 000-0000”。

  <TextField
      type={'custom'}
      keyboardType='numeric'
      returnKeyType='done'
      underlineColorAndroid='rgba(0,0,0,0)'
      value={this.state.maskedPhone}
      onChangeText={text => {
      this.setState({
            maskedPhone: text,
            phone: text.replace(/\D/g, '').substring(1)
      
         });
      }
      formatText={this.formatText}
  />

不知何故,我可以屏蔽文本,但没有像这样的国际代码 (+1)

formatText = text => {
   let x = text.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
   let maskedText = !x[2]
     ? x[1]
     : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');

   return maskedText;
 };

由于它是实时调用的,因此仅在字符串的开头添加“+1”并不能解决问题,因为它最终会将输入值更改为 +1 (111) 111-1111。
谢谢你!

 const input = '1234567890'; const re = /(\d{3})(\d{3})(\d{4})/; const output = input.replace(re, (_, a, b, c) => `+1 (${a}) ${b}-${c}`); console.log(output); // +1 (123) 456-7890

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM