Brosto
Brosto

Reputation: 4565

Javascript regular expression numeric range

Could someone help with a regular expression. I'm trying to format a phone number and handle an range of extension digits. I tried using a range [1-5], but that doesn't seem to work.

$(".phone").text(function(i, text) {
    if(text.length == 10) { //this portion works fine
        text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        return text;
    }else if (text.length > 10) { //this is where I need help
        text = text.replace(/(\d{3})(\d{3})(\d{4})(\d{[1-5]})/, "($1) $2-$3 x$4");
        return text;
    }
});

Is there a regular expression to handle a range of numbers here?

Upvotes: 0

Views: 2701

Answers (2)

Adrian Wragg
Adrian Wragg

Reputation: 7401

Your use of {[1-5]} is invalid. { and } indicate that the number of matches is between the two numbers contained within it (either parameter can be omitted), whilst [1-5] matches one character out of 1, 2, 3, 4 or 5. You need:

    text = text.replace(/(\d{3})(\d{3})(\d{4})(\d{1,5})/, "($1) $2-$3 x$4");

instead. For more information, see this QuickStart on repetition.

Upvotes: 1

David M
David M

Reputation: 72840

Yes, omit the square braces and use a comma.

\d{1,5}

Upvotes: 2

Related Questions