I am searching for a regular expression in JavaScript that can detect balanced parentheses within a phone number. The pattern I currently have is /^([1]{0,1})\s?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{

When entering a phone number, the following format must be followed:

  • The phone number may start with a "1," which is optional.
  • There can be a space after the starting digit, which is also optional.
  • An opening parenthesis "(" is optional.
  • This should be followed by 3 digits and then a closing parenthesis ")"
  • After that, there can be spaces, no space at all, or a hyphen "-"
  • Another optional opening parenthesis "("
  • Another set of 3 digits followed by a closing parenthesis ")"
  • Then another round of options for space, no space, or a hyphen "-"
  • Finally, one more optional opening parenthesis "("
  • Followed by 3 digits

Examples: 5555555555, 555 555 5555, 555-555-5555, (555)-(555)-5555

Examples cont.: 1 555 555 5555, 1555 555 5555, 1555-555-5555, 1-555-555-5555, 1 (555) (555) 5555


/^([1]{0,1})\s?\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$/

The regex above works on most cases but fails if an opening parentheses is used without a closing parentheses like in the examples below. If this issue could be fixed, it is appreciated.Please help!

Additional examples: 1 (555-555-5555 and 555) 555 5555

Answer №1

This regular expression

/^1?[- ]?(?:(?:\d{3}|\(\d{3}\))[- ]?){2}\d{4}$/

is a perfect match for the examples given

For real-time example, check out:

Answer №2

Utilize JavaScript to automatically generate a regex based on a valid format list, ensuring that any phone number within the list adheres to the specified format.

"Automatic creation of a regex using script" in practice and demonstration:

const validFormat = ["5555555555", "555 555 5555", "555-555-5555"
, "(555)-(555)-5555" , "1 555 555 5555", "1555 555 5555"
, "1555-555-5555", "1-555-555-5555", "1 (555) (555) 5555"];

let uniqueListTmp = new Set();

for(const s of validFormat) {
    let tmp1 = s.replace(/\d/g, "\\d");
    let tmp2 = tmp1.replace(/([\(|\)])/g, "\\$1");
    uniqueListTmp.add(tmp2);
}

let regexAsString = "^(";
for(const s of uniqueListTmp) {
    regexAsString += s + "|";
}

regexAsString = regexAsString.replace(/\|$/, ")$")
const regex = new RegExp(regexAsString);

const invalidInput = ["555", "5 5 5", "5-5-5"];
const validAndInvalidInput = validFormat.concat(invalidInput);

for(const s of validAndInvalidInput) {
    console.log(s, ' -> ', regex.test(s));
}

Output in the Console:

5555555555  ->  true
555 555 5555  ->  true
555-555-5555  ->  true
(555)-(555)-5555  ->  true
1 555 555 5555  ->  true
1555 555 5555  ->  true
1555-555-5555  ->  true
1-555-555-5555  ->  true
1 (555) (555) 5555  ->  true
555  ->  false
5 5 5  ->  false
5-5-5  ->  false

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the distinctions between Vue JS and React JS?

As I delve into learning Vue Js and React Js, my search for a detailed comparison between the two on Google left me unsatisfied. I came across resources answering the singular questions "What is Vue js?" and "What is React Js," but none that directly comp ...

Issues with returning undefined values in JSON with Node.js and AngularJS

I have developed an application that communicates with an API to retrieve and display data. The process involves entering a username in the client input, which is then sent to the server. Upon checking, everything seems to be working fine at this stage. H ...

A custom JavaScript function designed to facilitate the downloading of a file that includes the user's input directly to the user

Is there a way to use javascript to generate a file based on user input and provide it as a download without storing it on the server? For instance, imagine a scenario where a user is using an application and they want to download their work by clicking ...

I am struggling to find the correct way to fetch images dynamically from Cloudinary and display them as backgrounds. How should I go about implementing this feature successfully

I have been trying to figure out why I am unable to retrieve the image from cloudinary. My goal is to use the image as a background when posting, but it seems like I am not fetching the image correctly. function Post({post}){ return( <div ...

Error 404.0 - This WebApi Application is currently unable to locate the requested file. The

After attempting to deploy a WebApi application on a Windows 2008R2 server with IIS 7.0, without making any changes in the IIS Manager settings, I encountered an issue. The same application runs smoothly on our development server which has the same versio ...

Can a Bluetooth speaker in a car be utilized for noise cancellation?

While using my ANC earphones one day, I had a thought. The earphones were nearly able to drown out the noise of the car. This got me thinking: could ANC technology be used with car speakers and mobile phone apps? Although it might be challenging to resp ...

The onClick event handler fails to trigger in React

Original Source: https://gist.github.com/Schachte/a95efbf7be0c4524d1e9ac2d7e12161c An onClick event is attached to a button. It used to work with an old modal but now, with a new modal, it does not trigger. The problematic line seems to be: <button cla ...

What could be causing this slider to malfunction in Firefox?

I have recently developed a slider on this page: While the slider functions smoothly in Chrome, I am facing compatibility issues with Firefox. Can anyone shed some light on why this might be happening? Here is the HTML, CSS, and JS code used for the slid ...

Vue.js state not updating issue solved

Issue Resolved I encountered a problem with a VueJS component that is supposed to load and display a list of services from the backend in a table. Despite successfully fetching data from the API, the table remained empty. This component is integrated with ...

"Facing issues with Update Panel working synchronously instead of asynchronously

In my Master page, I have included a Script Manager as shown below: <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> Within the content page, there is an Update Panel containing a DataList and a Button structured li ...

Is there a simple way to display all the data from a JSON object even if the contents are unknown beforehand?

Greetings! I am Pearson's dictionary api. Here is a glimpse of what I receive from an api call: { "status": 200, "offset": 0, "limit": 10, "count": 10, "total": 135, "url": "/v2/dictionaries/entries?headword=dog", "results": [ { ...

The result of filtering multiple data using checkboxes in Vuetify is not displaying as expected

I am currently working on developing a straightforward task scheduler that includes filtering options using checkboxes. Below is the snippet from my vue file: Within my templates section, <fieldset> <legend>TASK STATUS</legend> ...

Simply click and drag a document from your file explorer directly into the desired text field to instantly generate a clickable

I am interested in dragging a file from our Windows server and dropping it onto a text area on a webpage. The link that would be generated will look something like this: <a href="\\fileserver\folder\pizza_2.pdf">filename.pdf< ...

The error handler in AngularJS $http service is always left wanting for a call

Here's the code snippet I'm currently using: $http .post('/api/login', $scope.user) .success(function (data, status, headers, config) { // code }) .error(function (data, status, headers, config) { // code }); It seems to be functi ...

Is there a way to transfer the selected item's id from the dropdown to the Django form action URL?

Issue My problem is that I need to pass the ID from the selected transaction item in the dropdown to the form action URL 'cart_add'. I have successfully retrieved the ID from the selected dropdown value, but I am struggling to pass this ID to the ...

What causes the React Query cache to be cleared upon page reload?

Hi there, I am new to Next.js and React Query. I would really appreciate any help or advice. I apologize for any mistakes in my English language skills. Currently, I am using Next.js v12 and React Query v3, along with the React Query DevTools. On one of ...

Utilizing JQuery to populate DIVs with JSON information

Hey! I recently received some helpful advice from a coding expert, and now I'm in the process of restructuring my code based on these recommendations: When using $.each(), you have the option to return true or false. If you return false, the loop wi ...

Selecting an item with Material UI AutoComplete now automatically clears the value

After making a selection, I want to clear the value in the input field immediately. Currently, the value is cleared on blur but not upon selection. <Autocomplete disabled={showTextField} className="center-vertically" options={listOfDependencies ...

Node.js - CSRF Protection Token Undefined

I've been facing challenges with setting up CSRF token generation, and I seem to be missing something. server.js: // configuration ====================================================================== var express = require('express'); va ...

Is there a way to update the parameter name in an array.map function?

I'm a little unsure. Is there a way to dynamically change the marker parameter to marker1, marker2, marker3, and so on depending on the number of elements in the map? Currently, I have this code but I would like each element in the map to have a mark ...