Last active
December 29, 2022 12:45
-
-
Save Hiweus/75f1a2a7d98c4b61360c5280cc4ddd8c to your computer and use it in GitHub Desktop.
Methods to format masks in javascript, the second one is more generic to be implemented in any language
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
/* | |
* the first implementation is simpler but not much smart because, if a pattern long than value is passed | |
* to function all remaining pattern will be write to outputValue and not crop immediately | |
* for all purposes use second function, the first one is only a option more compact for understanding | |
*/ | |
function makeString(value, pattern) { | |
let position = 0 | |
return pattern.replace(/#/g, () => { | |
if(position >= value.length) { | |
return '' | |
} | |
return value[position++] | |
}) | |
} | |
function makeString(value, pattern) { | |
let positionValue = 0 | |
let outputValue = '' | |
for(const i of pattern) { | |
if(positionValue >= value.length) { | |
break | |
} | |
if(i === '#') { | |
outputValue += value[positionValue++] | |
} else { | |
outputValue += i | |
} | |
} | |
return outputValue | |
} | |
makeString('5531993455698', '+## (##) #####-####') | |
// '+55 (31) 99345-5698' | |
makeString('123077', '###.###.###-##') | |
// '123.077' | |
makeString('12307775488', '###.###.###-##') | |
// '123.077.754-88' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment