Home > Mobile >  Sanitize phone number with regular expressions
Sanitize phone number with regular expressions

Time:12-24

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.

CodePudding user response:

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

  • Related