Skip to content

Instantly share code, notes, and snippets.

@akarca
Created September 24, 2018 13:11
Show Gist options
  • Save akarca/d3a44e2a629d8581179cab086a012fbf to your computer and use it in GitHub Desktop.
Save akarca/d3a44e2a629d8581179cab086a012fbf to your computer and use it in GitHub Desktop.
credit card formatter
var getFormattedValue = function (value, blocks, delimiter) {
var result = '',
currentDelimiter;
var blocksLength = blocks.length;
// no options, normal input
if (blocksLength === 0) {
return value;
}
blocks.forEach(function (length, index) {
if (value.length > 0) {
var sub = value.slice(0, length),
rest = value.slice(length);
currentDelimiter = delimiter;
result += sub;
if (sub.length === length && index < blocksLength - 1) {
result += currentDelimiter;
}
// update remaining string
value = rest;
}
});
return result;
};
getFormattedValue("1234567812345678", [4,4,4,4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment