DAY 16
0

# 今日kata

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"
``````

## 構想&解法

``````function createPhoneNumber(numbers) {
let prefix = numbers.slice(0, 3).join('')
let body = numbers.slice(3)
body.splice(3, 0, '-')
body = body.join('')
return `(\${prefix}) \${body}`
}
``````

## 其他解法觀摩

``````function createPhoneNumber(numbers){
var format = "(xxx) xxx-xxxx";
for(var i = 0; i < numbers.length; i++)
{
format = format.replace('x', numbers[i]);
}
return format;
}
``````

• 先把字串格式以`format`存入，數字以`x`取代
• For loop迴圈遍歷numbers陣列，一一替代`x`

``````function createPhoneNumber(numbers){
return numbers.join('').replace(/(...)(...)(.*)/, '(\$1) \$2-\$3');
}
``````

## 整理用法

### 字串.replace()

``````function replacer(match, p1, p2, p3, offset, string) {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
return [p1, p2, p3].join(' - ');
}
var newString = 'abc12345#\$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
console.log(newString);  // abc - 12345 - #\$*%

// p1代表匹配([^\d]*)的字串  ----> 非任意數字(亦不包含符號)
// p2代表匹配((\d*)的字串    ----> 任意數字
// p3代表匹配([^\w]*)的字串  ----> 非文字
``````

``````function createPhoneNumber(numbers){
return numbers.join('').replace(/(...)(...)(.*)/, '(\$1) \$2-\$3');
}
``````

`.`代表`單一字元`
`*`代表`匹配前一個字元0~多次`

• \$1=前3個字元
• \$2=第4~6的字元
• \$3=第7個字元以後的所有字元