2

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!!

0

1 Answer 1

3

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"

Sign up to request clarification or add additional context in comments.

1 Comment

Totally awesome, this is exactly what I needed! Thank you so much! I will accept the answer as soon as possible! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.