Codewars Spawn 1 – [regular generated Phone Number] -6Sku – Creat Phone Number
Problem 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.
Write a function that takes an array of 10 integers (between 0 and 9) and returns a string of those numbers as phone numbers.
Ex. :
createPhoneNumber([1.2.3.4.5.6.7.8.9.0]); // => returns "(123) 456-7890"
Copy the code
Their thinking
- Convert an array to a string
- Regular replacement
(* * * * * * - * * * *
The problem solving
-
The second argument in the string.prototype.replace () method can use $n to insert the matching NTH parenthes-matched String. Note:
- You need a RegExp object as the first argument.
n
Is a non-negative integer. The value range is[1, 100)
function createPhoneNumber(numbers) {
return numbers.join(' ').replace(/(\d{3})(\d{3})(\d{4})/.'($1) $2 - $3');
}
Copy the code
- test
console.log(createPhoneNumber([1.2.3.4.5.6.7.8.9.0])); / / "(123) 456-7890"
Copy the code
Codewars selected solution
Once you have successfully submitted your answer, you can browse other people’s solutions for best practices and clever solutions.
Choice solution 1:
function createPhoneNumber(numbers) {
numbers = numbers.join(' ');
return ` (${numbers.substring(0.3)}) ${numbers.substring(3.6)}-${numbers.substring(6)}`
}
Copy the code
Selected solution 2:
function createPhoneNumber(numbers) {
return numbers.join(' ').replace(/ (...). (...). / (. *).'($1) $2 - $3');
}
Copy the code
My solution is similar to this one, but it’s more compatible.
Solution 3:
function createPhoneNumber(numbers) {
var n = numbers;
return (
'(' +
n[0] +
n[1] +
n[2] +
') ' +
n[3] +
n[4] +
n[5] +
The '-' +
n[6] +
n[7] +
n[8] +
n[9]); }Copy the code
It’s not elegant, but some commenters say it’s the fastest solution. [stand hand]
Topic Related knowledge
- String.prototype.replace()
- String.prototype.substring()
- Regular expression
Welcome to star
Thanks open Source, Peace.