2

我一直在玩弄电话号码创建功能。它看起来像

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 位数字的逻辑。

4

3 回答 3

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;
}
于 2013-10-20T04:46:16.263 回答
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
...
于 2013-10-20T04:53:49.253 回答
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);
}
于 2013-10-20T04:55:04.350 回答