Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sanitize phone number with regular expressions

I have a component that is outputing a phone number with this format:

+1 (234) 567 - 8900

And I need this format:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2345678900

so target the inital +1 and then all brackets, dashes and spaces so I can perform a str.replace(regex, "").

What would be the regular expression to achieve this?

Until now I achieved with this expression:

/[\s()-]+/g

selecting everything but the initial +1.

enter image description here

I could add the + sign to the square bracket, but not the1 since I only want to target the first occurrence

Thanks in advance.

>Solution :

You can use

^\+1|[^0-9]+

You need to replace the found matches with an empty string. See the regex demo.

Details:

  • ^\+1+1 at the start of string
  • | – or
  • [^0-9]+ – one or more chars other than digits.

JavaScript demo:

const regex = /^\+1|[^0-9]+/g;
const text = '+1 (234) 567 - 8900';
console.log(text.replace(regex, ''));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading