frenchie
frenchie

Reputation: 51937

javascript combining multiple regex

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.

Upvotes: 2

Views: 115

Answers (2)

kalley
kalley

Reputation: 18462

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'))
               );
    }
}

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Try this:

TheText = TheText.replace(/(\d{1,2})(?=(?:\d{2})+$)/g, '$1 ');

Upvotes: 2

Related Questions