0

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?

0

2 Answers 2

2

Yes, omit the square braces and use a comma.

\d{1,5}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Happy to help! I've added a link to a guide that'll give more information if you need it.

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.