Live formatting of phone numbers using regular expressions

For my AngularJS project, I am looking to format phone numbers as they are being typed, without relying on any external library.

The desired format is: 99 99 99 99 99

var phone = tel.replace(/\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*(\d{2})\D*/, '$1 $2 $3 $4 $5');

The issue I encountered is that the regular expression only formats the number once it has been fully typed. Is there a way to make it work while the number is still being entered?

I attempted a modified version of the regular expression:

var phone = tel.replace(/\D*(\d{2})\D*(\d{0,2})?\D*(\d{0,2})?\D*(\d{0,2})?\D*(\d{0,2})?\D*/, '$1 $2 $3 $4 $5');

However, this resulted in unnecessary additional spaces being added. Any suggestions on how to improve the regex?

Answer №1

While you insist on wanting it to be "straight forward," it is important to note that artificially restricting the solution to just regex may not be the most effective approach for your problem.

Why is that? The issue lies in the fact that your problem requires the addition of new characters (spaces) conditionally to the output. This poses a challenge as the standard .replace() method is not capable of handling such conditional formatting.

A more efficient solution would involve utilizing a combination of regex and other JavaScript functions to address the conditional aspect:

// Extract only the digits from the input string
var phoneDigits = tel.replace(/\D/g, "");
// Combine the first 5 pairs of digits with spaces,
// accommodating for standalone digits if the total count is odd.
var phone = (phoneDigits.match(/\d\d?/g) || []).slice(0,5).join(" ");

(Using || [] ensures that the match does not return null when no digits are found.)

Answer №2

One way to achieve this is by utilizing a cascade style pattern.

var phone = tel.replace(/\D*(?:(\d{2})\D*(?:(\d{2})\D*(?:(\d{2})\D*(?:(\d{2})\D*(?:(\d{2})\D*)?)?)?)?)?/, '$1 $2 $3 $4 $5');

 \D* 
 (?:
      ( \d{2} )                     # (1)
      \D* 

      (?:
           ( \d{2} )                     # (2)
           \D* 

           (?:
                ( \d{2} )                     # (3)
                \D* 

                (?:
                     ( \d{2} )                     # (4)
                     \D* 

                     (?:
                          ( \d{2} )                     # (5)
                          \D* 
                     )?
                )?
           )?
      )?
 )?

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

Issue with date and time range in SQL query when using PHP AJAX

I've been struggling with a major issue for the past 4 days, and I'm really hoping to find a solution here. After countless unsuccessful attempts, I've turned to this platform for help. The problem at hand involves using a SQL Server databa ...

Creating a Dynamic Tree View Component in AngularJS Using JSON Data

I am new to AngularJS and I need help creating a TreeView Structure from a JSON Object. Here is an example of my Return JSON Object: var categoryTree = [{Name:'Item1', Childnodes : {}, id: 1}, {Name:'Item2', Childnod ...

Parsing JSON data results in a string output

After realizing that my initial post was not clear enough, here are more details. Jade: meta(name='revObj', content=(JSON.stringify('#{rev[1]}'))) The resulting HTML from Jade: <meta name="revObj" content=""{ companyAddress: &apo ...

Using jQuery, you can submit a form easily

In my work with Django, I am developing a quiz web application that requires a form submission after answering each question. The questions are displayed correctly, but I am facing an issue when trying to submit the form with the answers. The answers to t ...

Single-way binding in ng-bind for Angular JS 1.3 or higher with a conditional ternary expression

Is it accurate to use one-time binding for a ternary condition within the data-ng-bind directive? <span data-ng-bind="::model.boolean ? 'json.item.value1' : 'json.item.value2'"></span> or <span data-ng-bind=":: ...

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Tips for emphasizing the letters of the alphabet used in search functionality with Angular

Is there a way to highlight specific alphabets in the searched list instead of highlighting the entire word? Currently, when filtering the memberOffice and memberFacilities lists based on the alphabet entered in the search field, the entire text is highlig ...

Firefox experiencing trouble handling flexbox overflow

Having some trouble with a test project that involves using flexbox. The task at hand is to create a dashboard with multiple lists of cards arranged side-by-side with infinite overflow. I was able to achieve this layout, however, the issue arises when eac ...

Tips on displaying a selected choice | Utilizing Material UI Autocomplete

I have successfully fetched data from an API and used it as options in Material UI Autocomplete. However, when I select an option and send it back to the API using a POST request, the selected category is displayed as a number (0) instead of text, as shown ...

Sending data to another page by selecting a list item

Being new to web programming and JavaScript, I am facing a scenario where I have a list of requests displayed on one page and I need to pass the ID of the selected request to another page to display all the details of that particular request. I am strugg ...

My AngularJS ng-show functionality is not functioning as expected. I have already reviewed the syntax and still encountering issues

Having trouble with my ng-show, it's not functioning as expected <div class="form-group"> <label class="control-label col-sm-4">NotesTest:</label> <div class="col-sm-4"> <textarea class="form-control ...

"Adjust the placement of a personalized marker on a Google Map using google-map-react

I have incorporated google-map-react into my React project and I have designed custom markers. The markers are displayed at the correct location but from the top left corner: https://i.sstatic.net/e6lGN.png The red dot indicates the exact location. Howe ...

The perfect method for creating template literals using a function

I have a function that accepts an argument called id and returns a template literal: const generateTemplate = (id) => { return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; dis ...

Ways to retrieve information from a JSON using Regular Expression

I'm struggling with regular expressions and can't seem to find a solution to my problem. The JSON response from my service looks like this: "{\"Version\":14,\"Collections\":[{\"Id\" ...

Third Party Embedded Video requiring SSL Certificate

I am currently facing an issue where I am trying to embed videos from a website that does not have an SSL certificate. This is causing my own website to appear insecure when the page with the embedded video loads, despite the fact that my website has its ...

Troubleshooting a GetStaticProps problem in Next.js

I'm currently facing an issue with retrieving posts from my WordPress site. After running tests on the URL endpoint, it seems to be functioning properly with client-side rendering. However, when I attempt to utilize the getStaticProps function, the re ...

Encountering a 403 error when attempting to upload files from Angular to a Micron

I have encountered an issue while attempting to upload multiple files to the Micronaut Rest API. The uploading process works seamlessly with Postman and Swagger in the Micronaut Rest API, but when using the Angular app, the POST method throws a 403 HTTP er ...

Listener for a special event in Three.js

As I embark on my journey with Three js, I find myself in search of a unique event listener that seems to elude me online. I am curious whether it is feasible to execute a specific action when the first-person viewer enters an object. Any advice would be ...

Why does app.post function while router.post does not seem to work?

I have encountered an issue while logging in with React on the front end. The process goes to my node/Express/Passport backend and I am able to successfully log in when it reaches the backend. However, I am facing difficulties in communicating that informa ...

Is there a way to accelerate the webpack bundling process when using React during development?

Forgive me for what may seem like a silly question, but I am just beginning to explore the world of JavaScript and React. In my project, I am using React on the frontend and Django on the server side. Currently, I am unable to use React routing, so I have ...