Jane Fred
Jane Fred

Reputation: 1489

Regular expression to ignore the numbers after length reaches 10

I want number in this format

(123)-456-7890

The maximum length assigned is 10.

The regular expression used to obtain the above format is:

if (onlyNums.length === 10) {
            const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4})/, '($1) -$2-$3');

If length>10 I want the above format for the number and to ignore the rest of the digits(right trim).

How can I do that?

Upvotes: 3

Views: 245

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

If you remove the if condition and add a "catch-all" regex .* at the end, it will ignore whatever comes after the 10th digit:

const number = onlyNums.replace(/(\d{3})(\d{3})(\d{4}).*/, '($1) -$2-$3');

This assumes that onlyNums actually contains nothing but digits (and at least 10 of them). Otherwise, the result might be unexpected.

Test it live on regex101.com.

Upvotes: 3

Related Questions