Skip to content

Instantly share code, notes, and snippets.

@arbaouimehdi
Last active March 20, 2020 23:52
Show Gist options
  • Save arbaouimehdi/fbf81e0cd24d4d7f97e42250c2c2cba6 to your computer and use it in GitHub Desktop.
Save arbaouimehdi/fbf81e0cd24d4d7f97e42250c2c2cba6 to your computer and use it in GitHub Desktop.
/*!
* description: Format Phone Numbers
* Output: (+XXX) XXX-XXXXXX => (+212) 671-415075
* @phone
*/
function formatPhone(phoneNumber, format) {
// Replace X by each number on a specific position
for (let i = 0, l = phoneNumber.length; i < l; i++) {
format = format.replace(
"X",
phoneNumber[i],
);
}
return format;
}
// Test using an array
const num = [2,1,2,6,7,1,4,1,5,0,7,5];
console.log(formatPhone(num, "(+XXX) XXX-XXXXXX"));
// Test using a String
const num2 = "212671415075";
console.log(formatPhone(num2, "(+XXX) XXX-XXXXXX"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment