Last active
          March 1, 2021 19:33 
        
      - 
      
- 
        Save johnatandias/cfcad23fd23bbe16d2a9b18de2ae80aa to your computer and use it in GitHub Desktop. 
    Format value to pattern
  
        
  
    
      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 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