Categories
JavaScript Answers

How to define a regular expression to validate US phone numbers with JavaScript?

Spread the love

Sometimes, we want to define a regular expression to validate US phone numbers with JavaScript.

In this article, we’ll look at how to define a regular expression to validate US phone numbers with JavaScript.

How to define a regular expression to validate US phone numbers with JavaScript?

To define a regular expression to validate US phone numbers with JavaScript, we write a regex to match the groups of numbers.

For instance, we write

const re = /^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$/;

to use [0-9]{3} to match the groups of 3 digits.

We use [0-9]{4} to match the group of 4 digits.

^ matches start of the string.

$ matches end of the string.

Conclusion

To define a regular expression to validate US phone numbers with JavaScript, we write a regex to match the groups of numbers.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *