Skip to content

Instantly share code, notes, and snippets.

@dhoko
Last active July 15, 2016 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhoko/fc5eba7a2d382327157e to your computer and use it in GitHub Desktop.
Save dhoko/fc5eba7a2d382327157e to your computer and use it in GitHub Desktop.
Apply a mask to a String
/**
* Format an input from a given mask, key per key
* - XXXX-XXX-XXX-XXX => 1111-222-333-444
* - XXXX XXXX XXXX => 1111 2222 3333
* - XX/XX => 11/22
* @param {String} mask
* @return {Function}
*/
const maskInput = (mask = '') => {
const maskLength = mask.length;
const maskSepators = mask.match(/[^X]/g);
let maskReplaced = '';
let i = 0;
/**
* Input string to format following the mask
* @param {String} input
* @return {String}
*/
const matchMask = (input = '') => {
// Remove a string from the input
if (maskReplaced.length > input.length) {
maskReplaced = maskReplaced.slice(0, input.length);
i = maskReplaced.length;
return maskReplaced.trim();
}
// Do not update the string if position > length of da mask
if (maskLength > i) {
// Append anything !X
if ('X' !== mask.charAt(i)) {
maskReplaced += mask.charAt(i);
i++;
}
maskReplaced += input.charAt(input.length - 1);
}
i++;
return maskReplaced.trim();
};
/**
* Convert a string to match the pattern
* @param {String} input
* @return {String}
*/
const full = input => {
maskReplaced = ''; i = 0;
return input
.split('')
.reduce((acc, key) => acc = matchMask(acc + key), '');
};
/**
* Return a string without its mask
* @param {String} input
* @return {String}
*/
const filtered = (input = '') => {
return input
.split('')
.filter(key => -1 === maskSepators.indexOf(key))
.join('')
.trim();
};
const size = () => mask.length;
/**
* Convert an input masked to another one masked
* @param {String} input
* @return {String}
*/
const update = (input = '') => full(filtered(input.trim()));
return {update, matchMask, full, filtered, size};
};
@dhoko
Copy link
Author

dhoko commented Dec 17, 2015

maskInput('XXXX XXXX XXXX XXXX');
  .full('1111222233334444'); // 1111 2222 333 444

maskInput('XX/XXXX');
  .full('112015'); // 11/2015

maskInput('XXX XX:XX:XX');
  .full('1st191510'); // 1st 19:15:10

maskInput('XXXX XXXX XXXX XXXX')
  .filtered('1111 2222 333 444') // 1111222233334444

maskInput('XXX XX:XX:XX');
  .update('1st 19:15:AA'); // 1st 19:15:AA

With an event listener:

const mask = maskInput('XXXX XXXX XXXX XXXX');
input
  .addEventListener('input', e => {
    e.target.value = mask.set(e.target.value);
 })

@dhoko
Copy link
Author

dhoko commented Jul 15, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment