Created
September 24, 2018 13:11
-
-
Save akarca/d3a44e2a629d8581179cab086a012fbf to your computer and use it in GitHub Desktop.
credit card formatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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