Twitter Classic Interview Questions:
Write a function, [1,2,3,4,5,6,7,8,9,0] return "(123) 456-7890" phone number.
Method 1: String stitching
This is the most straightforward way to form a phone number by manually splicing each section. I believe that many novices answer this question through methods, but real experts will never be satisfied with answering a question in the roughest way. Let’s see what other tricks we can do~
function getPhoneNum(arr) { return "(" + arr[0] + arr[1] + arr[2] + ") " + arr[3] + arr[4] + arr[5] + "-" + arr[6] + arr[7] + arr[8] + arr[9]; } (getPhoneNum([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));
Better writing of string splicing:
function createPhoneNumber(numbers) { const part1 = (0, 3).join(''); const part2 = (3, 6).join(''); const part3 = (6, 10).join(''); return `(${part1}) ${part2}-${part3}`; } (createPhoneNumber([1,2,3,4,5,6,7,8,9,0])); // Output: (123) 456-7890
This method takes advantage of the template string characteristics of ES6, and uses the arrayslice
Method to extract the required part. It is not difficult to see that the expression of es6 is more semantic, and it is not as mechanical and rough as ordinary string splicing. Comparing the two writing methods, it is not difficult to see that there are many results returned.Single quotes
And put+
Replaced with$
, Let's talk about ES6Template string
。
Template string
ES6 template strings (also known as template literals) provide a new way to create strings that use backticks (
) instead of single quotes (' ') or double quotes (" "). Template strings bring many conveniences and enhancements, especially when you need to embed expressions or variables in strings. The following is used$
Several main benefits of symbols (for interpolation):
1. Multi-line string
- Template strings can span multiple lines without the need to use escape characters `` or connectors
+
。
const message = `This is a Crossing Multiple lines String`; (message); // Output:// This is a// Cross// Multiple lines// String
2. Variable interpolation
- use
${}
The syntax can directly insert variables or expressions into strings without using string splicing.
const name = "Alice"; const age = 30; const message = `My name is ${name},I'm this year ${age} age。`; (message); // Output: My name is Alice, I am 30 years old this year.
3. Expression interpolation
- Not only can you insert variables, but any valid JavaScript expression can also be inserted.
const a = 5; const b = 10; const result = `a + b The result is ${a + b}`; (result); // Output: The result of a + b is 15
4. Readability and simplicity
- Template strings make the code easier to read and concise, especially when dealing with complex string splicing.
// Traditional wayconst greeting = "Hello, " + name + "! You are " + age + " years old."; // Template stringconst greeting = `Hello, ${name}! You are ${age} years old.`;
5. Tag template
- Template strings support tag templates, which is an advanced feature that allows you to prefix a template string with a function name that handles the template string.
function highlight(strings, ...values) { let result = ''; ((str, i) => { result += str + (values[i] || ''); }); return `<span style="color: red;">${result}</span>`; } const name = "Bob"; const age = 25; const message = highlight`My name is ${name}, and I am ${age} years old.`; (message); // Output: <span style="color: red;">My name is Bob, and I am 25 years old.</span>
Method 2: for loop through the array and replace method
function getPhoneNum(arr){ let format = "(xxx) xxx-xxxx" for (let i = 0; i < ; i++) { format = ("x", arr[i]) } return format } (getPhoneNum([1,2,3,4,5,6,7,8,9,0]));
This method uses string variablesformat
Determine the format"(xxx) xxx-xxxx"
. Use againfor
Loop through eachx
Will bearr
Replace corresponding numbers in the array. Compared with string splicing, the readability of this method is much stronger. You can imagine it extreme. If the input array has hundreds or even thousands of numbers, the code written using string splicing will be very wide! And it's very tiring to write.
Method 3: Use join and regular expressions
This method first concatenates all numbers into a string and then inserts the desired delimiter using a regular expression.
function createPhoneNumber(numbers) { const phoneNumber = (''); return (/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3"); } (createPhoneNumber([1,2,3,4,5,6,7,8,9,0]));
The advantage of this method lies in the simplicity of the code and the better performance. Although its expression is not very intuitive for beginners, whether you can write concise and strong performance code is an important indicator to distinguish between big shots and ordinary people.
Conclusion
All the above three methods can achieve the same effect. Which method to choose mainly depends on personal preferences or the needs of the specific scenario. For example, if you want your code to be more concise, you may tend to use Method 3; if you value the readability of your code more, you may choose Method 1 or Method 2.
The above is the detailed content of various implementation methods of JavaScript phone number formatting. For more information on JavaScript phone number formatting, please pay attention to my other related articles!