1

Im using replace() to filter phone numbers, but is it possible to leave a + if its at the beginning and remove all subsequent non-numeric values? I just want to create mask for mobile.

My example:

const maskPhone = (value, code) => {
  return value
    .replace(/\D/g, "")
    .replace(/(\d{4})(\d)/, "($1) $2")
    .replace(/(\d{5})(\d)/, "$1-$2")
    .replace(/(-\d{4})(\d+?)$/, "$1");
};

maskPhone(++32332+323232)

Expected result:

+(323) 32 323 232

So only one + is allowed at the start but for now it's allowed only numbers

Second question, how to pass value dynamically to this regexp?

Like this:

 const maskPhone = (value, code) => {
      return value
        .replace(/\D/g, "")
        .replace(/(\d{code})(\d)/, "($1) $2")
        .replace(/(\d{5})(\d)/, "$1-$2")
        .replace(/(-\d{4})(\d+?)$/, "$1");
    };
Orion447
  • 351
  • 4
  • 16
Ksenia
  • 950
  • 6
  • 24

1 Answers1

4

Reading your code with the multiple replacements containing - and 4 digits will not result in the expected result, as there is no - and there are no 4 digits.

To get your first desired result, you can remove a plus sign not being at the start of the string, OR remove any non digit except + using

(?<!^)\+|[^\d+]+

For example:

const maskPhone = (value) => {
  return value
    .replace(/(?<!^)\+|[^\d+]+/g, "")
    .replace(/(\d{3})(\d\d)(\d{3})(\d{3})/, "($1) $2 $3 $4")
};

console.log(maskPhone("++32332+323232"));

To use \d{code} you would have to use the RegExp constructor instead of the literal notation as you can see on How do you use a variable in a regular expression?


If you can not use a lookbehind, you can use a capture group:

const maskPhone = (value) => {
  return value
    .replace(/^(\+)|[^\d\n]/g, (_, g1) => g1 ? g1 : '')
    .replace(/(\d{3})(\d\d)(\d{3})(\d{3})/, "($1) $2 $3 $4")
};

console.log(maskPhone("++32332+323232"));
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Thank you, but how replace just first one? – Ksenia Feb 14 '23 at 17:22
  • Thank you so much, could you pls help me, where I should set {15} to limit numbers with 15 chars? – Ksenia Feb 14 '23 at 17:40
  • @Ksenia Do you mean you want to only do the second replacement to the new format if there are 15 or less characters in total after the first replacement? Can you give an example string? – The fourth bird Feb 14 '23 at 17:49