Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Other possible solution for challenge 02/09 format phone number using regex #19

Open
tre-tom opened this issue Nov 30, 2023 · 0 comments

Comments

@tre-tom
Copy link

tre-tom commented Nov 30, 2023

There is a solution possible with format phone number using regexes and replacing groups. So whatever you put inside brackets, you can then reference in the replace clause using $1 $2 and so on.

Here is the code:

const formatPhoneNumber = (numbers) => numbers
    .reduce((output, number) => output + number, '')
    .replace(/([0-9]{3})([0-9]{3})([0-9]{4})/, '($1) $2-$3')

So I am first converting the numbers array into string using reduce.
Then I am creating regex groups in the left side of replace statement:

  • ([0-9]{3}) means first 3 digits will be accessible via $1
  • ([0-9]{3}) means next 3 digits will be accessible via $2
  • ([0-9]{3}) means last 4 digits will be accessible via $3

Then you can reference it in the right side of replace statement using ($1) $2-$3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant