Skip to content

Instantly share code, notes, and snippets.

@sdrew
Last active August 10, 2016 10:36
Show Gist options
  • Save sdrew/70fa8cde92a903a860b8222866ead3bb to your computer and use it in GitHub Desktop.
Save sdrew/70fa8cde92a903a860b8222866ead3bb to your computer and use it in GitHub Desktop.
var PhoneFormatMX = function (phone, display) {
var prefix = '';
var dash = 0;
var segment = 4;
phone = phone.replace(/\D/g, '');
dash = phone.length;
if (dash > 10) {
if (phone.indexOf('044') === 0 || phone.indexOf('045') === 0) {
prefix = phone.substr(0, 3);
phone = phone.slice(3);
} else if (phone.indexOf('00') === 0 || phone.indexOf('01') === 0) {
prefix = phone.substr(0, 2);
phone = phone.slice(2);
}
dash = phone.length;
}
while (dash > segment) {
phone = phone.slice(0, dash - segment) + '-' + phone.slice(dash - segment);
dash = phone.indexOf('-');
if (segment === 4 && (prefix.length > 0 || (prefix.length === 0 && phone.length === 11))) {
if (phone.indexOf('55') !== 0 && phone.indexOf('33') !== 0 && phone.indexOf('81') !== 0) {
segment = 3;
}
}
}
dash = phone.indexOf('-');
if (dash >= 0 && phone.match(/[-]/g).length > 1) {
if (display) {
phone = '(' + phone.slice(0, dash) + ') ' + phone.slice(dash + 1);
}
if (prefix.length === 0) {
prefix = '+'
} else {
prefix += display ? ' ' : '-';
}
}
return prefix + phone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment