I'm using a series of regex and jquery functions to format a textbox of 9 digits. The code looks like this:
function FormatBox() {
var TheText = $('#TheBox').val();
//remove leading 0
if (TheText.charAt(0) === '0') {
TheText = TheText.substring(1);
}
//take only digits
TheText = TheText.replace(/\D/g, '');
//take only the first 9 digits
if (TheText.length > 9) {
TheText = TheText.substring(0, 9);
}
//reformat string
TheText = TheText.replace(/(\d{1})?(\d{2})?(\d{2})?(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5');
//trim string
TheText = $.trim(TheText);
$('#TheBox').val(TheText);
}
function Start() {
$('#TheBox').keyup(FormatBox);
}
$(Start);
As it is, it all works fine but I'm looking to combine these rules that mix regex and jquery into one regex but I'm struggling to get it working. What do I need to do to add the constraints to the reformatted string to make is work? The jsFiddle is here.
Thanks.
thisinFormatBoxinstead of grabbing#TheBoxagain. Also why is everything written withLeadingCase? This is usually a convention for naming constructors.