Problem
- 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.
- 전화번호 형식으로 해당 숫자의 문자열을 반환하는 함수를 작성한다.
- 10개(0과 9 사이)의 정수 배열을 사용한다.
Solution 01
function createPhoneNumber(arr) {
arr = arr.join('');
return '(' + arr.substring(0, 3) + ') ' + arr.substring(3, 6) + '-' + arr.substring(6);
}
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); // (123) 456-7890
createPhoneNumber([1, 1, 1, 2, 2, 2, 3, 3, 3, 3]); // (111) 222-3333
Solution 02
function createPhoneNumber(arr) {
let format = '(xxx) xxx-xxxx';
for (let i = 0; i < arr.length; i++) {
format = format.replace('x', arr[i]);
}
return format;
}
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); // (123) 456-7890
createPhoneNumber([1, 1, 1, 2, 2, 2, 3, 3, 3, 3]); // (111) 222-3333
Solution 03
function createPhoneNumber(arr) {
return arr.reduce((total, i) => total.replace('x', i), '(xxx) xxx-xxxx');
}
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); // (123) 456-7890
createPhoneNumber([1, 1, 1, 2, 2, 2, 3, 3, 3, 3]); // (111) 222-3333
Solution 04
function createPhoneNumber(arr) {
return arr.join('').replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
}
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); // (123) 456-7890
createPhoneNumber([1, 1, 1, 2, 2, 2, 3, 3, 3, 3]); // (111) 222-3333
Solution 05
function createPhoneNumber(arr) {
return arr.join('').replace(/(...)(...)(.*)/, '($1) $2-$3');
}
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); // (123) 456-7890
createPhoneNumber([1, 1, 1, 2, 2, 2, 3, 3, 3, 3]); // (111) 222-3333