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.

3
  • And why don't you skip RegEx and use simple string replace? Commented Apr 21, 2017 at 14:18
  • @MirkoVukušić because he doesn't know the numbers he wants to change. So he has to use regex
    – Zooly
    Commented Apr 21, 2017 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 :) jsbench.me/ylj1rxzao8/1 Commented Apr 21, 2017 at 14:59

1 Answer 1

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;
3
  • \d Matches any decimal digit. Equivalent to [0-9] Easiest way to get what you want here
    – Zooly
    Commented Apr 21, 2017 at 14:22
  • @HugoTor Yes indeed.
    – cнŝdk
    Commented Apr 21, 2017 at 14:24
  • @chsdk: It worked. If I am having 1234.4567.7654.3456 exp 12 13, It will mask only digit not the "." or space. Desired output should be ******************* exp ***** Commented Apr 24, 2017 at 12:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.