Home > Article > Web Front-end > JavaScript Fun Question: Creating a Phone Number
Now provides an array containing 10 integers (0-9), requiring the return of a phone number string in the specified format.
Like this:
createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"
These numbers must be in the order they appear, and don’t forget the special symbols and spaces!
To be honest, when I saw this question for the first time, I was a little underestimated, and I quickly gave a popular solution.
Isn’t it just a matter of converting an array into a string, intercepting it, and then splicing it!
This phone number consists of three parts, the area code, the first half, and the second half:
function createPhoneNumber(numbers){ var areaCode = numbers.slice(0,3).join(""); var firstPart = numbers.slice(3,6).join(""); var secondPart = numbers.slice(6).join(""); return "(" + areaCode + ") " + firstPart + "-" + secondPart; }
This is the most direct method, but it is also the most versatile and scalable. solution.
What if the area code is 4 digits and the phone number is 8 digits? Wouldn't it require several changes?
The best is to give a general string template and give it according to the template.
Okay, now that you have thought of this step, let’s take a look at the writing method of an expert!
function createPhoneNumber(numbers){ var format = "(xxx) xxx-xxxx"; for(var i = 0; i < numbers.length; i++){ format = format.replace('x', numbers[i]); } return format; }
Well, that’s much better.
The above is the content of JavaScript interesting question: creating a phone number. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!