jQuery-Mask-Plugin
jQuery-Mask-Plugin copied to clipboard
How to apply mask to string value not element
All the examples and use cases seem to be on how to use the plugin to apply a mask to the value of an input field. However, I've run into a situation where I need to apply the mask to a raw string value and get the resulting mask.
for example I currently have this custom mask
function getPhoneMask (input, e, field, options){
let unmaskedVal = input.replace(/[^\d]/g, '');
let masks = ['(000) 000-00000000000', '+0 (000) 000-00000000', '+00 (000) 000-0000000', '+000 (000) 000-000000', '+0000 (000) 000-00000', '+00000 (000) 000-0000'];
let mask = unmaskedVal.length == 15 ? masks[5]: unmaskedVal.length == 14 ? masks[4] : unmaskedVal.length == 13 ? masks[3] : unmaskedVal.length == 12 ? masks[2]: unmaskedVal.length == 11 ? masks[1] : masks[0];
console.log(`mask: ${mask}`);
return mask
}
$('.phoneMask').mask(getPhoneMask, {
onKeyPress: function(input, e, field, options) {
let mask = getPhoneMask(input, e, field, options);
field.mask(mask, options);
}
});
This finds the value of each element with the .phoneMask class and applies the mask on load and on keypress.
however, let say i have a random string "1231231234" This value is not the value of an input element but just the value of some variable in my code. How can i apply my custom mask just to this value so that i would end up with (123) 123-1234