Skip to content

Instantly share code, notes, and snippets.

@alexlecco
Last active March 21, 2021 19:15
Show Gist options
  • Save alexlecco/5fca7bbca86771d6d959aea5047b6856 to your computer and use it in GitHub Desktop.
Save alexlecco/5fca7bbca86771d6d959aea5047b6856 to your computer and use it in GitHub Desktop.
mask a number
function format(mask, number) {
const string = number.replace('-','')
let result = ''
for(let iMask = 0, iString = -1; iMask < mask.length && iString < string.length; iMask += 1) {
const currentChar = mask.charAt(iMask)
result += currentChar === 'X' ? string.charAt(iString += 1) : currentChar
}
return result
}
const number = '1234567890'
const mask = 'XX-XXXXXXX-X'
console.log(format(mask, number))
const number = '1234567890';
var formatted = number.replace(/^(\d{2})(\d{7})(\d{1}).*/, '$1-$2-$3');
console.log(formatted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment