JavaScript Scratches

Regex Examples

Here are some common search patterns you might require. Feel free to adjust them according to your needs.

Phone Number

When you view the source code for this page, you may notice something odd.
The phone numbers all begin with something called a zero-width character because they may be represented as links (to dial a phone number), depending on the device used.
Check the Resources link for more about zero-width characters.

A typical North American phone number is commonly indicated like this:

⁠(123) ​456-7890

We will build the regex to find this pattern a piece at a time ...

First: look for 1 leading '(' parenthesis.

We have a regex that satisfies that condtion:

myReg = /^\((?![()])/;

Now we adjust it to look for a single opening parenthesis '(', followed by 3 digits, followed by a single closing parenthisis ')', and a single space.

This one does that:

myReg = /^(\({1}\d{3}\){1} )/

Next we need three digits for the exchange . . .

myReg = /^(\({1}\d{3}\){1} \d{3})/;

And the hyphen between exchange and phone . . .

This one:

myReg = /^(\({1}\d{3}\){1} \d{3}-{1})/;

Finally, 4 digits at the end, after the hyphen:

Last one:

myReg = /^(\({1}\d{3}\){1} \d{3}-{1}\d{4}$/;

Now you try:

Enter a phone number formatted thus: (or not)