Skip to content

Instantly share code, notes, and snippets.

@johnatandias
Last active March 1, 2021 19:33
Show Gist options
  • Save johnatandias/cfcad23fd23bbe16d2a9b18de2ae80aa to your computer and use it in GitHub Desktop.
Save johnatandias/cfcad23fd23bbe16d2a9b18de2ae80aa to your computer and use it in GitHub Desktop.
Format value to pattern
const formatToPattern = (value: string, pattern: string): string => {
const maskLength = [...pattern.matchAll(/#/g)].length
if (maskLength !== value.length) return value
let i = 0
return pattern.replace(/#/g, () => value[i++])
}
console.log(formatToPattern('99999999999', '(##) #####-####')) // (99) 99999-9999
console.log(formatToPattern('12345678989', '###.###.###-##')) // 123.456.789-89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment