0

I have to implement masking for a field through javascript and i have written a code and its working fine with alphanumeric characters or word but the below code is not able to mask the special character entered.

function addMask(value) {
        $(this).val(value.replace(/\w(?=\w{4})/g, "*"));
    }

its not able to mask the special characters.

neeraj bharti
  • 361
  • 1
  • 3
  • 20
  • Possible duplicate of [RegEx for Javascript to allow only alphanumeric](https://stackoverflow.com/questions/388996/regex-for-javascript-to-allow-only-alphanumeric) – GalAbra Jul 26 '19 at 12:40
  • First - `\d` matches only `[0-9]`, *not alpha characters* second, it's not a dupe b/c they are talking about special characters, not just alphanum. – mikeb Jul 26 '19 at 12:43
  • i have updated the question with passing word in regex. [a-zA-Z0-9] its not working will you send the correct syntax for regex as i am using /\[a-zA-Z0-9] (?=\[a-zA-Z0-9] {4})/g – neeraj bharti Jul 26 '19 at 12:44

2 Answers2

1

If you are just trying to mask an arbitrary input, possibly consisting of alpha, numeric, or special characters, then why not just try:

function addMask(value) {
    $(this).val(value.replace(/.(?=.{4})/g, "*"));
}

This would generate an output where everything except the last four characters are masked with *.

var input = "123456789";
console.log(input);   
output = input.replace(/.(?=.{4})/g, "*");
console.log(output);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

\d is the same as [0-9], you need to include whatever your "special" characters are in the set of characters to match.

You don't say what the special characters are, so I can't help with your exact problem.

If, say, your special characaters are a, b, or c you could do [abc0-9] instead of \d

mikeb
  • 10,578
  • 7
  • 62
  • 120