Marcos Di Paolo
Marcos Di Paolo

Reputation: 659

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:

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.

Upvotes: 1

Views: 812

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627180

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, ''));

Upvotes: 2

Related Questions