RegEx in JavaScript to mask only numbers and special character (/, space, -) in a string

I need to write a regex where it will mask the entire digit in the string.

For example:

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

      

or

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

      

I use:

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

      

the whole string is masked using the above regular expression.

+3


source to share


1 answer


The regex you are using does not give the expected result because it matches the entire string, so the whole string is masked .

Here's what you need:

var myregexp = /\d/g;

      

You just need to match \d

every 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, "*"));
      

Run codeHide result


Edit:

If you want to combine the white spaces and special characters such as _

and .

also, you can use the following Regex:

var myregexp = /[\d\._\s]/g;

      

+4


source







All Articles