javascript结合多个正则表达式

时间:2013-12-03 21:18:28

标签: javascript regex

我正在使用一系列正则表达式和jquery函数来格式化9位数的文本框。代码如下所示:

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

实际上,它一切正常,但我希望将这些将正则表达式和jquery混合在一起的规则组合成一个正则表达式,但我很难让它运行起来。要将重新格式化的字符串添加到约束中,我需要做些什么? jsFiddle是here

感谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:1)

这并没有将它全部放入1个正则表达式中,但它确实简化了一点:

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