如何防止libphonenumber-js在格式化数字时删除短划线



我想使用libphonenumber js来格式化电话号码。对于下面的代码,它总是删除破折号。我怎样才能保持仪表板?

const phoneNumber = parsePhoneNumber("+494021337342-53")
console.log("phoneNumber: ", phoneNumber, phoneNumber.formatInternational())
// +49 40 2133734253

库中没有本地方法可用于保留连字符,但是

您可以获得数字的国家格式,即

const nationalNumber = parsedPhoneNumber(phoneNumber).formatNational();

它会给你连字符的数字,然后替换圆括号(如果有的话(,并对其进行修剪;

let phoneNumber = nationalNumber.replace(/(|)/g,'').trim()

现在用连字符替换剩余空间

phoneNumber = phoneNumber.replace(' ','-');

然后你可以手动添加countryCode,就像这样,

phoneNumber = countryCode + phoneNumber. // you will have to find the country code

最新更新