Created
April 9, 2017 01:14
-
-
Save vgashic/0af16123e6d180ab0887cc794a2a70f5 to your computer and use it in GitHub Desktop.
JavaScript format number based on pattern
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
function formatNumber(numbers, pattern){ | |
//var pattern = '(999) 999-9999'; | |
var patternArray = pattern.split('').map(function(x) { return isNumber(x) ? null : x; }); | |
var resultArray = []; | |
var pos = 0; | |
for (var i = 0; i < patternArray.length; i++) { | |
if (patternArray[i] === null) { | |
patternArray[i] = numbers[pos]; | |
pos++; | |
} | |
} | |
return patternArray.join(''); | |
} | |
function isNumber(n) { | |
return n - parseFloat(n) + 1 >= 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment