Home > Web Front-end > JS Tutorial > JavaScript Fun Question: Creating a Phone Number

JavaScript Fun Question: Creating a Phone Number

黄舟
Release: 2017-02-04 15:46:39
Original
1404 people have browsed it

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"
Copy after login

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;  
}
Copy after login

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(&#39;x&#39;, numbers[i]);  
    }  
    return format;  
}
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template