Assuming you want the format "(123) 456-7890
":
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/D/g, '');
var match = cleaned.match(/^(d{3})(d{3})(d{4})$/);
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3];
}
return null;
}
Here's a version that allows the optional +1
international code:
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/D/g, '');
var match = cleaned.match(/^(1|)?(d{3})(d{3})(d{4})$/);
if (match) {
var intlCode = (match[1] ? '+1 ' : '');
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
}
return null;
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900') // => "(234) 567-8900"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…