3

I have to write a regex where it will mask all the digit in a string.

Eg:

Input: 1234567890 expiry date is 1211    
Output: ********* expiry date is ****

or

Input: 1211 and number is 1234567890</p>    
Output: **** and number is *********

I am using:

var myregexp = /^(?:\D*\d){3,30}\D*$/g;<br/><br/>

whole string is getting masked using the above regex.

cнŝdk
  • 28,676
  • 7
  • 47
  • 67
  • And why don't you skip RegEx and use simple string replace? – Mirko Vukušić Apr 21 '17 at 14:18
  • @MirkoVukušić because he doesn't know the numbers he wants to change. So he has to use regex – Zooly Apr 21 '17 at 14:23
  • 1
    @HugoTor, my first reflex is always to avoid RegEx (performance) if it can be done faster. however, in this case it's not possible, regex is pretty simple and there are 10 possible characters to replace. Loop is about 12% slower (Chrome), more code and less readable :) https://jsbench.me/ylj1rxzao8/1 – Mirko Vukušić Apr 21 '17 at 14:59

1 Answers1

4

The Regex you are actually using doesn't give the expected result because it matches the whole string, that's why whole string is getting masked.

Here's what you need:

var myregexp = /\d/g;

You just need to match \d each time and replace it with *, you can see it in this working Demo.

Demo:

var str = "1234567890 expiry date is 1211";

var myregexp = /\d/g;

console.log(str.replace(/\d/g, "*"));

Edit:

If you want to match white spaces and special characters such as _ and . too, you can use the following Regex:

var myregexp = /[\d\._\s]/g;
cнŝdk
  • 28,676
  • 7
  • 47
  • 67