christian
christian

Reputation: 177

regex - detect and replace more then two digits in string

As soon as there are more then two digits in a string, I want to replace only them the digits. Example:

allowed:

bla 22 bla bla

should be replaced:

bla 234 bla 8493020348 bla

to

bla *** bla ********** bla

The exact numbers don't matter - just 1-2 digits should be displayed and if there are more then 2, then they should be replaced.

This is what I've already tried, but it always replaces the whole string and not only the digits....further if 2 digits are accepted and later on there's a third digit it gets triggered as well..

  var regex = /^(?:\D*\d){3}/g;
  str = str.replace(regex, "**");

So this won't work:

bla 12 and so on 123

It will become:

**

But I want it to be like this:

bla 12 and so on ***

Thank you SO much in advance!!

Upvotes: 2

Views: 1228

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97130

One solution is to pass a callback function to String.prototype.replace() and use String.prototype.repeat() to put in the correct number of asterisks:

string = string.replace(/\d{3,}/g, (v) => '*'.repeat(v.length));

Complete snippet:

const string =  'bla 22 bla 234 bla 8493020348 bla';

const result = string.replace(/\d{3,}/g, (v) => '*'.repeat(v.length));

console.log(result); // "bla 22 bla *** bla ********** bla"

Upvotes: 3

Related Questions