我一直在玩电话号码创建者功能。它看起来像
createPhoneNumber(1) -- would return (000)000-0001
createPhoneNumber(5901) -- would return (000)000-5901
createPhoneNumber(18883141) -- would return (001)888-3141
function createPhoneNumber(number) {
//return properly formatted phone number
}
我无法弄清楚填充小于10位的数字的逻辑。
答案 0 :(得分:1)
function createPhoneNumber(number) {
var digitsGiven = number & number.length ? number.length : 0;
var digitZeros = 10-digitsGiven;
var phoneNumber = '(';
for (var i = 0; i < digitZeros.length; i++) {
phoneNumber += '0';
}
phoneNumber += number;
phoneNumber = phoneNumber.substr(0, 4) + ')' + phoneNumber.substr(4);
phoneNumber = phoneNumber.substr(0, 8) + '-' + phoneNumber.substr(8);
return phoneNumber;
}
答案 1 :(得分:1)
看看这是否有帮助:
function phone(num, format) {
var i = format.match(/0/g).length;
num = [].slice.call(num).reverse();
return format.replace(/0/g, function() {
return num[--i] || 0;
});
}
用法:
phone('12345', '(000)000-0000'); //=> (000)001-2345
phone('123456', '00-000-000'); //=> 00-123-456
...
答案 2 :(得分:0)
你想要str_pad
pn(1);
pn(5901);
pn(18883141);
function pn($num)
{
$pad = str_pad($num, 10, '0', STR_PAD_LEFT);
return '('.substr($pad, 0, 3).')'.substr($pad, 3, 3).'-'.substr($pad, 6, 4);
}