标签:javascrip substring data- function cep i++ pts ++ ext
题目:
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.
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
Solutions:
1:
function createPhoneNumber(numbers){
numbers = numbers.join(‘‘);
return ‘(‘ + numbers.substring(0, 3) + ‘) ‘
+ numbers.substring(3, 6)
+ ‘-‘
+ numbers.substring(6);
}
解题:就是拼接字符串没啥好说的
2:
function createPhoneNumber(numbers){
var format = "(xxx) xxx-xxxx";
for(var i = 0; i < numbers.length; i++)
{
format = format.replace(‘x‘, numbers[i]);
}
return format;
}
解题:熟练使用替换字符串也没啥好说的;
3:
function createPhoneNumber(numbers){
return numbers.join(‘‘).replace(/(...)(...)(.*)/, ‘($1) $2-$3‘);
}
正则用来检索、替换文本很厉害,也很简单,以后要留心。
标签:javascrip substring data- function cep i++ pts ++ ext
原文地址:http://www.cnblogs.com/shaoxiablogs/p/6072527.html