【问题标题】:Phone number regex pattern in JS replace() functionJS replace() 函数中的电话号码正则表达式模式
【发布时间】:2022-01-15 18:58:57
【问题描述】:

我正在尝试使用 replace() 函数验证电话号码模式。如果数字的第一个数字不是以 3 开头,并且数字长度不得超过总 10 位数字,我需要删除该数字的第一个数字,并在用户键入时删除长度为 10 后的其他输入数字。 这是我的代码:

function phoneNumber(element){
    if(element.value.length != 0){
        element.value = element.value.replace(/^0[^0-9].{9}/, '');
    }
}
<input type="text" name="phone" required oninput="phoneNumber(this)"/>

我想要的是,如果用户键入除 3 之外的第一个数字,那么该数字将被删除,并且该数字的总长度将为 10。 一些需要理解的案例:

3430215478 // acceptable
343454545454 // not acceptable and replace() should remove the last two digits 54
0347878788 // not acceptable and replace() should remove the first digit 0
+924544444 // not acceptable and replace() should remove the all the digits because it does not start with 3

我尝试了在 Internet 上找到的不同正则表达式,但在 replace() 函数中不起作用。 如果您能帮助我,我将不胜感激。

【问题讨论】:

标签: javascript html regex


【解决方案1】:

应该这样做:element.value.replace(/^[^3]+|^([0-9]{10}).*|[^0-9]+/g, '$1')

function phoneNumber(element)
{
  if (!element.value.length)
    return;

  element.value = element.value.replace(/^[^3]+|^([0-9]{10}).*|[^0-9]+/g, '$1')
}

/*
3430215478 // acceptable
343454545454 // not acceptable and replace() should remove the last two digits 54
0347878788 // not acceptable and replace() should remove the first digit 0
+924544444 // not acceptable and replace() should remove the all the digits because it does not start with 3
*/
<input type="text" name="phone" required oninput="phoneNumber(this)"/>

正则表达式包含由|分隔的3部分:

^[^3]+ - 这匹配字符串开头不是数字3的任何字符

^([0-9]{10}).* - 这部分做了两件事:首先它从字符串 ^([0-9]{10}) 的开头捕获 10 位数字,并匹配它之后的所有其他数字 .*

[^0-9]+ - 最后这部分匹配任何非数字字符

正则表达式匹配的任何字符都将被从正则表达式第二部分通过$1关键字(代表第一个捕获的组)捕获的10位数字替换

正则表达式末尾的gGlobal 标志,这意味着它将继续匹配正则表达式的每个部分,没有它,正则表达式将在第一次匹配时停止。

【讨论】:

  • 如果我在数字之间写入特殊字符,例如我写 34.!@3#787888979 这个正则表达式接受这个,这个正则表达式就会失败。 @vanowm
  • 谢谢伙计,现在它正在工作。你能解释一下这个正则表达式是如何检查模式的吗? $1 有什么作用?
  • 添加到答案中
【解决方案2】:

您可能需要考虑使用libphonenumber-js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多