Utilize Regular Expressions to validate phone numbers

Currently tackling a Regex challenge.

let phones = ['321-1234567','+355 321 1234567','0103 1234500', '00 355 3211234567' ]

Desired results:

3211234567
+3553211234567
+3551031234500
+3553211234567

Implemented solution:

phones.forEach(phone => {
      phone = phone.replace(/^0+/,'+355').replace(/[^+\d]+/g, '')
      console.log(phone)
    })

Output:

3211234567
+3553211234567
+3551031234500
+3553553211234567 --->incorrect , supposed to be: +3553211234567

The current implementation only works for the first three elements in the array, failing to handle the last case where two zeros need replacing with + when starting with 00.

To address this,

How can I achieve this using Regex, or should I resort to conditional statements like if phone.startsWith()?

This question offers unique circumstances compared to other solutions available online.

Answer №1

Transforming phone numbers in an array using JavaScript:

let phones = ['321-1234567','+355 321 1234567','0103 1234500', '00 355 3211234567' ]

phones = phones.map(r => r
  .replace(/^00/,'+')
  .replace(/^0/,'+355')
  .replace(/[^+\d]+/g, '')
)

console.log(phones)

Answer №2

If you need to manipulate phone numbers, here's a useful code snippet:

let phones = ['321-1234567','+355 321 1234567','0103 1234500', '00 355 3211234567' ]
for (const phone of phones) {
  console.log(
      phone.replace(/^0{1,2}/, (x) => x=='00'?'+':'+355')
           .replace(/(?!^\+)\D/g, ''))
}

Insights:

  • .replace(/^0{1,2}/, (x) => x=='00'?'+':'+355')
    - This regex pattern matches either '00' or '0' at the beginning of the string and replaces it with either '+' or '+355'. The ternary operator is used for conditional replacement.
  • .replace(/(?!^\+)\D/g, '') eliminates any non-digit characters except '+' if it appears at the start of the string.

Regex breakdown:

  • ^0{1,2} - ^ marks the beginning of the string and 0{1,2} matches one or two occurrences of zero.
  • (?!^\+)\D - (?!^\+) acts as a negative lookahead that rejects the match if the character immediately following is '+' at the string's start. \D matches any non-digit character.

Answer №3

The issue lies in this specific line of code replace(/^0+/,'+355'). You should modify it to be replace(/^0+/,'+')

phones.forEach(phone => {
      phone = phone.replace(/^0+/,'+').replace(/[^+\d]+/g, '')
      console.log(phone)
    })

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

The Javascript driver allows me to search MongoDB's vast database of 500 million documents using regular expressions on two specific fields, without relying on a predefined schema

My MongoDB database contains approximately 500 million documents structured like this: { "_id": objectId, "Name": "John Smith", "Address": "132, My Street, Kingston, New York 12401" } I am looking to ...

Creating collapsible tables with hook functionality in Material-UI

Having trouble resolving this issue, I am seeking assistance with my handleClick() function which is supposed to collapse and expand all table rows simultaneously. The code snippet demonstrating the issue can be found here. Can anyone explain why it is not ...

Having difficulty with utilizing array.every() properly, leading to inaccurate results

Struggling to validate an array of IDs using a custom validator in a nestjs project. The issue arises when passing the array of IDs to a service class for database querying, as the validation always returns true even with incorrect IDs. Snippet of the cus ...

Do we require 'function()' when declaring an event?

I currently have two scripts included in my project: <script src="../js/createopp.min.js"></script> <script src="../js/validation.min.js"></script> Within the first script, there is a line calling a function from the second script ...

When it comes to Redux, is it considered an anti-pattern to pass an event from a presentational component to a container component

As a newcomer to Redux, I am challenging myself to rebuild an old React app using this technology in order to gain proficiency. However, I am facing a significant challenge regarding where to place the logic within the application. My understanding is tha ...

$set { "array.variable.value" :"newvalue"} utilize a different term besides "variable" or implement a new variable

When working with mongoose to store user data, one of the attributes is an array called items. In my additems.js file: const User = require('../models/User'); var array = user.items; array.indexOfObject = function (property, value) { ...

When the state of the grandparent component is updated, the React list element vanishes in the grandchild component. Caution: It is important for each child in a list to have a unique

In my development project, I've crafted a functional component that is part of the sidebar. This component consists of 3 unique elements. ProductFilters - serves as the primary list component, fetching potential data filters from the server and offer ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

Using jQuery to add elements to another element

My goal is to create a button that, when pressed, will change the theme color on my jQuery mobile test site. Imagine my HTML parent div looks like this: <div id="firstPage" data-role="page"> I want to be able to click the button and have it add da ...

Opt for res.render() over res.send() when developing in Node.js

I recently developed an image uploader for ckeditor. After uploading a file, I need to send back an html file that includes the name of the image to the client. Check out the code snippet below: router.post('/upload', function (req, res, next) ...

Setting a dynamic default value for a Combobox using React Widgets

Currently delving into the world of javascript, I am working on creating a web client that showcases data from a database. Utilizing react.js and integrating react-widgets for some user-friendly widgets. One widget in particular, the combobox, pulls its da ...

Invoke actions when clicking outside of components

Currently, I have a HeaderSubmenu component that is designed to show/hide a drop-down menu when a specific button is clicked. However, I am now trying to implement a solution where if the user clicks anywhere else in the application other than on this drop ...

Modifying the select option dynamically once it has been activated does not produce the desired result

I'm encountering an issue with the select element. My goal is to programmatically change the selected option, ensuring compatibility with IE6. However, setting the selectedIndex with the desired value doesn't work when the control is disabled. To ...

React Native application crashes on Android 12 and above when run on an emulator

Currently in the process of creating a music application named Wavelet. Listed below are my dependencies: package.json Typically, I debug on an Android 11 emulator; however, when switching to an Android 12 emulator or using my physical device running on A ...

The registration feature powered by JQuery is experiencing technical difficulties and not functioning

Having trouble with a registration system on my website at *. When someone registers, it should either show an error message or display "true" if the registration is successful. I have a javascript file (http://pastebin.com/mv9CWZcT) set up to redirect the ...

Implement a nested feature within the Accordion component

I am currently working on a project using Next.js and TypeScript. Within this project, I have implemented an accordion component as shown below: import React, { useEffect, useState } from 'react'; import classes from './Accordion.module.scss ...

Step-by-step guide for properly transferring PHP MySQL data to ChartJs

I am looking to create bar charts and pie charts using ChartJs, with data fetched from php and mysql. Specifically, I want to generate a bar chart that illustrates the statistics of male and female students, along with the total number of students. The des ...

What is the significance of declaring a variable outside of a JavaScript function? (Regarding jQuery and #anchor)

In my jQuery function, I needed to determine the current #anchor of the page. To achieve this, I utilized the jQuery URL Parser plugin. $.fn.vtabs = function() { alert("The current anchor is "+$.url.attr('anchor')); } Initially, the code c ...

When utilizing jQuery lightbox to pull data from a database using PHP/Ajax, it may require a double click the

Encountering a strange issue where I must click on specific buttons with unique IDs. These IDs are then sent through Ajax to a PHP script, which searches for corresponding entries in the database. The retrieved data is then displayed in a jQuery lightbox. ...

Creating clickable links with Regex for 'a href' tags only, excluding 'img src' tags

After extensive effort, I am still struggling to find a reliable solution for my issue. The task at hand is to convert all http/https links within a string into clickable links, specifically targeting only those embedded in the 'href' attribute o ...