Created
November 8, 2014 18:27
-
-
Save ronmichael/cb1e0c58ebe533ded4af to your computer and use it in GitHub Desktop.
Format a phone number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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