Search code examples
javascriptregexp-replace

JavaScript regexp for phone number does not match


I would like to ask for help with following issue:

I have following regexp:

var r = /^(\+455\ )(\d{3})(\d{1,3})(\d{1,3})$/

i would like to use this regexp to replace number and separate this number by spaces, for example like this : "+455 123 123 123".

I was expecting, that regexp above will do following job: when i have "+455 " and 4 digits, it would return this: "+455 123 1", but it only works from 5th digit in second group and output is following:

'+455 1111'.replace(r,"$1$2 $3 $4"); is returning this: '+455 1111' (i expected +455 111 1)

and '+455 11121'.replace(r,"$1$2 $3 $4"); is returning this: '+455 111 2 1' (I expected +455 111 21)

Can anyone help pls and let me know, where I am doing mistake in declaring regexp? Or anywhere else...

Thank you in advance.

Brgds, Tom


Solution

  • The pattern ^(\+455 )(\d{3})(\d{1,3})(\d{1,3})$ matches at least 5 digits due to the {1,3} in the quantifiers.

    If you make the last group optional, there can be a match for the 3rd group from the 7th - 9th digit in group 4

    You can omit the backslash before the space as well in this part \

    ^(\+455\ )(\d{3})(\d{1,3})(\d{1,3})?$
    

    Regex demo

    const regex = /^(\+455 )(\d{3})(\d{1,3})(\d{1,3})?$/;
    [
      "+455 123123123",
      "+455 1111",
      "+455 11121"
    ].forEach(s =>
      console.log(s.replace(regex, "$1$2 $3 $4"))
    );