Skip to content

Instantly share code, notes, and snippets.

@imparvez
Created June 16, 2019 17:01
Show Gist options
  • Save imparvez/1a29792bb1a88a0ba804235b02f2e03f to your computer and use it in GitHub Desktop.
Save imparvez/1a29792bb1a88a0ba804235b02f2e03f to your computer and use it in GitHub Desktop.
Format Phone Number using JavaScript
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