2

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.

1
  • You could use this in FormatBox instead of grabbing #TheBox again. Also why is everything written with LeadingCase? This is usually a convention for naming constructors. Commented Dec 3, 2013 at 21:34

2 Answers 2

2

Try this:

TheText = TheText.replace(/(\d{1,2})(?=(?:\d{2})+$)/g, '$1 ');
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, good start but it doesn't add the spaces at the right place and doesn't validate the length. Almost there, upvoted!
1

This doesn't put it all into 1 regex, but it does simplify it a bit:

$(Start);

function Start() {

    var box = $('#TheBox').keyup(FormatBox);

    function FormatBox() {

        box.val($.trim(box.val()
                       .replace(/(^0+|\D)/g, '') // gets rid of all leading zeros (in case of paste) and any non-numbers
                       .substring(0, 9) // or .replace(/^(.{0,9}).*/, '$1')
                       .replace(/(\d)?(\d{2})?(\d{2})?(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5'))
               );
    }
}

2 Comments

Possibly the following between your replace clauses instead of the final substring: replace(/^(.{0,9}).*/, '$1'). It makes little practical difference, but seems clearer to me rather than the magic number of 13.
@ScottSauyet good point. I'm not sure why I felt I needed the substring at the end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.