Regex to replace the first 5 numbers, regardless of anything in between?

I am trying to achieve the following match

Enter

123-45-6789 123456789 1234 

Reg Ex (s) Tried with the output:

 \d{5} 

123-45-6789

12345 6789

1234

 \d{2,3} 

123 - 45 - 678 9

123456789

123 4

 \d{3}-{0,1}\d{2} 

123-45 -6789

12345 6789

1234

I need to provide this regular expression to replace the method, and I do not want to replace the " - ", it should replace only the first 5 digits without changing the format:

Expected Result

123 - 45 -6789

12345 6789

1234

EDIT

In the above examples, the outputs are:

1> all mapped to global regex 2> Bold numbers are expected to match

goal

I need to hide the SSN, for example: 444-55-6666 becomes ### - ## - 6666 and 444556666 becomes ##### 6666. Without format restriction.

+5
source share
2 answers

You want to combine and replace these first five digits:

 var str = `123-45-6789 123456789 1234 ` console.log(str.replace(/^(\D*\d\D*){5}/gm, function(match) { return match.replace(/\d/g, '*'); })) 
+1
source

Here are other ways to look at this:

  • You want to ignore all non-numeric characters and then get the first five numbers

     input.replace(/\D/g,'').substr(0,5); 
  • You want to combine five numeric characters wherever they appear in the input

     input.match(/\d/g).slice(0,5); 

There is almost always more than one way to approach a problem. If you cannot understand how to do what you want, try reformulating the problem until you find something that you can do.

+1
source

Source: https://habr.com/ru/post/1270141/


All Articles