Description:
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
Example:
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
my answer:使用正则表达式
function createPhoneNumber(numbers){
var pattern = /(d{3})(d{3})(d{4})/
pattern.test(numbers.join(''));
return '('+ RegExp.$1 +')'+ ' ' + RegExp.$2 +'-'+RegExp.$3;
}
console.log(createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));
best answer:
function createPhoneNumber(numbers){
return numbers.join('').replace(/(...)(...)(.*)/, '($1) $2-$3');
}
other answer :不使用正则
function createPhoneNumber(numbers){
var format = "(xxx) xxx-xxxx";
for(var i = 0; i < numbers.length; i++)
{
format = format.replace('x', numbers[i]);
}
return format;
}