Created
June 16, 2019 17:01
-
-
Save imparvez/1a29792bb1a88a0ba804235b02f2e03f to your computer and use it in GitHub Desktop.
Format Phone Number using JavaScript
This file contains 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
function formatNumber(number, format = 'xxx-xxx-xxx') { | |
let result = '', | |
curIndex = 0; | |
format.split('').forEach(char => { | |
if(char.toLowerCase() === 'x') { | |
result += number.charAt(curIndex) | |
curIndex++ | |
} else { | |
result += char | |
} | |
}) | |
return result | |
} | |
console.log(formatNumber('9619452263')) // "961-945-226" | |
console.log(formatNumber('9619452263', 'XX-XX-XX-XX-XX')) // "96-19-45-22-63" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment