Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  184] [ 4]  / answers: 1 / hits: 16719  / 12 Years ago, wed, january 9, 2013, 12:00:00

I am attempting to implement an auto-formatter in JS, such that if I have a given value (e.g. 12345678) and I have a given format (e.g. XX.XX.XX OR XX-XX-XX OR XX/XX/XX OR XXX-XXXX), I can auto-format my initial value to any of the given formats.



The required format will vary, so it needs to be able to take any given format and reformat the original value to match.



I have no idea if its possible or how to go about it. Any help appreciated.



Thanks,



Clara


More From » regex

 Answers
5

Something like this ?



function format(mask, number) {
var s = ''+number, r = '';
for (var im=0, is = 0; im<mask.length && is<s.length; im++) {
r += mask.charAt(im)=='X' ? s.charAt(is++) : mask.charAt(im);
}
return r;
}

console.log(format('XX.XX.XX', 12345678)); // logs 12.34.56
console.log(format('XXX-XXXX', 12345678)); // logs 123-4567
console.log(format('XX-XX-XX', 12345678)); // logs 12-34-56
console.log(format('XX/XX/XX', 12345678)); // logs 12/34/56
console.log(format('XX/XX/XX/XX/XX', 12345678)); // logs 12/34/56/78


No regex engine was harmed in the making of this code.



Fiddle


[#80988] Tuesday, January 8, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
havenbilliec

Total Points: 324
Total Questions: 106
Total Answers: 94

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;