【问题标题】:Regular expression to ignore the numbers after length reaches 10正则表达式忽略长度达到10后的数字
【发布时间】:2019-10-06 14:50:08
【问题描述】:

我想要这种格式的数字

(123)-456-7890

分配的最大长度为 10。

用于获取上述格式的正则表达式为:

if (onlyNums.length === 10) {
            const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');

如果长度>10 我想要上面的数字格式并忽略其余数字(右修剪)。

我该怎么做?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    如果您删除 if 条件并在末尾添加“catch-all”正则表达式 .*,它将忽略第 10 位之后的任何内容:

    const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4}).*/, '($1) -$2-$3');
    

    这假设onlyNums 实际上只包含数字(并且至少包含 10 个数字)。否则,结果可能出乎意料。

    测试它live on regex101.com

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多