我正在尝试替换下面的字符串,如下所示:
我正在考虑的一些案例是:
//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
下面是我编写的js代码,但这并没有为我提供上述情况的正确结果。
var lastphdigit = phone.replace(/\d{3}(?!\d?$)/g, 'xxx-');
您可以尝试以下方法:
function formatPhoneNumber(phone) {
//remove all non-digit characters
phone = phone.replace(/\D/g, '');
//if phone number is longer than 10 digits, keep only the last 10 digits
if (phone.length > 10) {
phone = phone.slice(-10);
}
//format the phone number as xxx-xxx-xxxx
phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, 'xxx-xxx-$3');
return phone;
}
//example
var phone1 = "+1-555-555-1234";
var phone2 = "1(800)555-0199";
var phone3 = "555 555 1234";
var phone4 = "9898871234567";
console.log(formatPhoneNumber(phone1)); //xxx-xxx-1234
console.log(formatPhoneNumber(phone2)); //xxx-xxx-0199
console.log(formatPhoneNumber(phone3)); //xxx-xxx-1234
console.log(formatPhoneNumber(phone4)); //xxx-xxx-4567
只需将输入的最后 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