JavaScript Regular Expression for standardizing phone number input

I'm working with an input for a phone number in French format which can accept two different formats:

  1. 0699999999
  2. +33699999999

There is currently no check for the length of the number.

In the database table, the field is varchar 12, but shorter inputs are allowed. The constraints are as follows: the input must contain only digits from 0 to 9, and an optional '+' sign is accepted if it appears at the beginning of the string, not afterwards.

Currently, I am using Angular with a directive that includes this expression:

var transformedInput = inputValue.replace(/[^0-9]/g, ''); 

I would like to include the optional leading '+' sign, how can I achieve this? Thank you.

Answer №1

To add flexibility, you can consider making the plus sign optional:

if (/\+?\d*/.test(textToCheck)) {
    // Match found
} else {
    // No match
}

The variable textToCheck holds the string you want to examine. By using \+ as a literal and adding a question mark, it allows for an optional plus sign.

If your main objective is only to verify the existence of a plus sign, omit the question mark. In such cases, using a regex might be unnecessary overhead. Instead, trim the string and inspect the first character directly to look for the plus sign.

Answer №2

Modify this text to

let adjustedValue = originalValue.replace(/[^0-9\+]/g, '').replace(/(.)\+/g, '$1'); 

Please note - the above code will only add a + if one is present in the input


The function accomplishes the following steps:

  1. Retains the + symbol during the first replacement operation
  2. Eliminates any + symbols that come after another character during the second replacement operation

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

Utilize an A-frame feature to dynamically enable or disable a component through a

I have set up a virtual environment using A-frame () with some raining effects and a button. What I want to achieve is to have a function executed when the button is clicked, that function should remove the rain component from the scene. Here is the code s ...

Obtain the data from a nested array

I'm facing a situation where I have the following code: var obj = { level1 : { level2 : 'value' } }; I also have another object: var returnData = { value: "level1.level2", anotherThing: "level1" }; The goal is to ...

In Vue(tify), transitions require children to have keys, but in this case, there are no tags present as children

Trying to implement a transition on a list using Vue and Vuetify, but encountering the error message vue.runtime.esm.js?2b0e:619 [Vue warn]: <transition-group> children must be keyed: <v-card> I attempted the Vuetify approach <v-fade-transi ...

interactive navigation menu with countdown feature

Looking to create an HTML/jQuery dropdown menu, but encountering a problem. The goal is for the div to slide down when the mouse hovers over the "games" navigation button and only disappear after 5 seconds of the mouse being out, not instantly. Here's ...

Tips on saving a cookie using universal-cookie

I followed a solution on Stack Overflow to set a cookie in my React application. However, the cookie expires with the session. Is there a way I can make this cookie persist beyond the session so it remains even when the browser is closed and reopened? ex ...

Trouble sliding with Material UI Slider

I've encountered an issue with my Material UI slider - it doesn't slide when clicked and dragged. I followed one of the examples on the Material UI website (https://material-ui.com/components/slider/) and included an onChange function. The values ...

The efficiency of XSL Template is significantly impacting loading time

Hello there, I am facing a challenge with my webpage's loading speed due to the code provided below. Can you assist me in optimizing it? <xsl:template match="Category" mode="CategorySelectorScript"> <xsl:variable name="ThisCateg ...

The PHP script is not receiving any data when checking if the value is set in the $_POST variable

I'm attempting to transmit values from a JavaScript file using POST method to a PHP page. Here is the AJAX code: let userInput = $input.val(); $.ajax({url: "../checkout/test.php", type : 'post', data : {'userInput': user ...

Updating a variable within a directive's scope does not automatically propagate changes to the corresponding controller function

Within my directive, there is a controller variable named page that increases when the button in the directive is pressed. However, I noticed that the line scope.alertPage(), which triggers the controller function, does not show this change. Even after cli ...

Choose between creating an observable pipe within a function or storing it in a variable

Currently, I have a functional code snippet that leverages the Angular service to create an Observable pipeline. This pipeline utilizes operators like mergeMap, filter, map, and shareReplay(1) to manage user authentication and fetch the onboarding status f ...

AngularJS is throwing an error stating that the URL ID is undefined

I am developing an application that utilizes angularjs with codeigniter as the backend. Within my URL, I have http://localhost/submit/1234, with 1234 serving as the ID. Within my angularjs setup: var singlepost = angular.module('singlepost', [ ...

How can text selection be ordered using a non-array model in AngularJS?

I am using the ng-options="ref as display for (ref, display) in method to showcase a non-array object in a dropdown menu, but I am encountering difficulties when it comes to sorting the values in the dropdown. Can anyone advise me on how to utilize the or ...

Attempting to achieve a carousel animation using jQuery

Upon loading the page, only one character out of four is displayed. Two arrows are provided - one on the left and one on the right. Clicking on the left arrow causes the current character to fade out and the previous character to fade in. Clicking on the r ...

How does a database contribute to the functionality of a redux application?

Recently, I started exploring redux and finally understood the architecture behind it. In a single page redux application where all data is stored in a central store and updated through frontend actions, what purpose does the back-end and database serve? ...

A versatile Material UI paper that adjusts its dimensions dynamically

Utilizing Material-UI's Paper component (https://mui.com/components/paper/), I've encountered a scenario where the content within the Paper element needs to be dynamic. <Paper className="modal" elevation={3}> ...Content </Paper ...

Issue with Many to Many Relation Query in Objection JS, Postgres, and Express Resulting in 'TypeError: Cannot Read Property 'isPartial' of Null' Error

I have a challenge connecting the 'products' table to the 'tags' table using a many-to-many relationship structure with the 'products_tags' table. Upon executing const product = await Product.relatedQuery('tags').fi ...

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

Failure of event watcher on dynamically updated content

Any help would be greatly appreciated! :) I am currently using JavaScript to dynamically add fields to a document, but I have noticed that the event listener only works on predefined fields. For instance, in the code snippet below, the 'lozfield&apo ...

Having difficulty with the javascript click() function in an html document

Thank you in advance for checking this out. In my web application, users can choose options from four separate drop-down menus. Once a selection is made, the software triggers a click() function that generates a new span element within a div: var activeF ...

Unusual behavior observed within for loop; code within not running as expected

I will be presenting my code along with some images to illustrate the issue at hand. Something as simple as declaring a variable or using the log function results in the json being undefined. Upon entering text into the input field, the ajax call is trigg ...