Last active
March 21, 2021 19:15
-
-
Save alexlecco/5fca7bbca86771d6d959aea5047b6856 to your computer and use it in GitHub Desktop.
mask a 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
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)) |
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
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