How to format a phone number from (000) 000 - 0000 to a international phone format

Viewed 181

Hello I have a string value of '(000) 000-0000' and I need to convert it into a string value of '+10000000000' in the international phone format. How do I go about that? Thanks. EDIT: Thank you for the quick reply. I forgot to include my previous code snippet that wasn't working for me.

  const phoneNumber = '(000) 000-0000';

  const convertedPhoNum = phoneNumber.replaceAll('\\D+', '');

  const intPhoneNumber = '+1' + convertedPhoNum;
  console.log(intPhoneNumber)

2 Answers

Remove all non-numeric characters from the string, then prepend "+1":

const original = "(000) 000-0000";

const result = "+1" + original.replace(/\D/g, '');

console.log(result)

The answer by @Spectric should be fine, but you could also use a regex replace approach here:

var original = "(000) 000-0000";
var output = original.replace(/\((\d{3})\) (\d{3})-(\d{4})/, "+1$1$2$3");
console.log(original + "\n" + output);

Related