Skip to content

Instantly share code, notes, and snippets.

@moinism
Created January 17, 2021 10:21
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 moinism/961971d5142703b87db804f1ba05f47f to your computer and use it in GitHub Desktop.
Save moinism/961971d5142703b87db804f1ba05f47f to your computer and use it in GitHub Desktop.
A simple method to format/mask numbers or any text in JavaScript.

Here's a demo if you wanna play with it:

https://codepen.io/moinism/pen/PoGXrdj?editors=1010

P.S: It's just a simple and lazy implementation, could be made more generalized.

P.P.S: It does not mask the input. It's just a method which can be used anywhere.

/*
Usage Example:
format('xxxx-xxxx', 12345678, '-') // outputs: 1234-5678
*/
/**
*
* @param {String} mask
* @param {Number} number
* @param {String} delimeter
*
* @returns {String}
*/
function format(mask, number, delimeter) {
if (!number) return mask;
delimeter = delimeter || "-";
let count = 0;
const numberString = number.toString();
return mask
.split(delimeter)
.map((group) =>
group.replace(/x/g, (match) => { // change 'x' to any other char if needed
return numberString.charAt(count++) || match;
})
)
.join(delimeter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment