Skip to content

Instantly share code, notes, and snippets.

@carlos3g
Created February 19, 2023 19:05
Show Gist options
  • Save carlos3g/9c8f30745613792c6445d6842bfe39a5 to your computer and use it in GitHub Desktop.
Save carlos3g/9c8f30745613792c6445d6842bfe39a5 to your computer and use it in GitHub Desktop.
const DIGIT = '9';
const ALPHA = 'A';
const ALPHANUM = 'S';
const toPattern = (value: string, pattern: string): string => {
const resultArray = pattern.split('');
const values = value.split('');
let index = 0;
let i = 0;
for (i; i < resultArray.length; i++) {
if (index >= values.length) {
if (resultArray.length === values.length) {
return resultArray.join('');
}
break;
}
if (
(resultArray[i] === DIGIT && values[index].match(/[0-9]/)) ||
(resultArray[i] === ALPHA && values[index].match(/[a-zA-Z]/)) ||
(resultArray[i] === ALPHANUM && values[index].match(/[0-9a-zA-Z]/))
) {
resultArray[i] = values[index];
index++;
continue;
}
if (resultArray[i] === DIGIT || resultArray[i] === ALPHA || resultArray[i] === ALPHANUM) {
return resultArray.slice(0, i).join('');
}
if (resultArray[i] === values[index]) {
index++;
continue;
}
}
return resultArray.slice(0, i).join('');
};
export { toPattern };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment