Skip to content

Instantly share code, notes, and snippets.

@ronmichael
Created November 8, 2014 18:27
Show Gist options
  • Save ronmichael/cb1e0c58ebe533ded4af to your computer and use it in GitHub Desktop.
Save ronmichael/cb1e0c58ebe533ded4af to your computer and use it in GitHub Desktop.
Format a phone number
/*
Formats a typical US phone number, including an extension (if preceeded by something like x, ex, ext, etc).
Crude but adequate.
*/
String.prototype.formatPhone = function () {
var phone = this;
if (!phone) return "";
var ex;
var ph = phone;
var exidx = ph.search(/[e|x]/);
if (exidx >= 0) {
ex = ph.substring(exidx).replace(/\D/g, '');
ph = ph.substring(0, exidx);
}
ph = ph.replace(/\D/g, '');
if (ph.indexOf('1') == 0) ph = ph.substring(1);
if (ph.length != 10) return phone;
ph = ph.substring(0, 3) + '-' + ph.substring(3, 6) + '-' + ph.substring(6);
if (ex) ph += " x" + ex;
return ph;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment