Sophie
Sophie

Reputation: 123

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

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)

Upvotes: 2

Views: 746

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521457

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

Upvotes: 1

Spectric
Spectric

Reputation: 31992

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)

Upvotes: 2

Related Questions