提问人:Karan Nayyar 提问时间:10/10/2023 最后编辑:Karan Nayyar 更新时间:10/12/2023 访问量:67
带有括号或特殊字符的电话号码掩码 [重复]
Phone Number Masking with brackets or special characters present [duplicate]
问:
我正在尝试替换以下字符串,如下所示:
我正在考虑的一些案例是:
//Ignore Special char
phone = "+1-555-555-1234"
result = xxx-xxx-1234
phone = "1(800)555-0199"
result = xxx-xxx-0199
//Ignore Space
phone="555 555 1234"
result = xxx-xxx-1234
//if length >10 so only consider the last 10 digit
phone = "9898871234567" //only consider 8871234567
result = xxx-xxx-4567
//If phone number contains spaces,parenthesis or some garbage character only consider digits.
phone = "9898871234567)"
result = xxx-xxx-4567
以下是我所处理的js代码,但这并没有为我提供上述情况的正确结果。
var lastphdigit = phone.replace(/\d{3}(?!\d?$)/g, 'xxx-');
答:
1赞
Robby Cornelissen
10/10/2023
#1
只需将输入的最后 4 个字符附加到 :xxx-xxx-
const format = (phone) => `xxx-xxx-${phone.slice(-4)}`;
console.log(format("+1-555-555-1234")); // xxx-xxx-1234
console.log(format("1(800)555-0199"));// xxx-xxx-0199
console.log(format("555 555 1234")); // xxx-xxx-1234
console.log(format("9898871234567")); // xxx-xxx-4567
因此,要么您希望看到解决其他情况,并且需要将这些情况添加到问题中,要么您将事情过于复杂化。
评论
0赞
Karan Nayyar
10/12/2023
我还有另一种情况,电话号码字符串末尾可能会有一些垃圾字符,如空格、括号等。我只想显示一个字符串 xxx-xxx-4567 而不是 xxx-xxx-567)。有什么可能的方法来实现这一点吗?
评论