21

Usage of this code is to show only the last four digits of an input.

Here I want to replace this "(/.(?=.{4})/g, '*')" '4' with variable 'mask' . Something like that.

x.value = x.value.replace(/.(?=.{+mask+})/g, '*');

Any suggestion plz

function myFunction(mask) {
    var x = document.getElementById("cc");
    x.value = x.value.replace(/.(?=.{4})/g, '*');
}
<input type="text" id="cc" onkeyup="myFunction(4)" style="text-align:right">
user2864740
  • 60,010
  • 15
  • 145
  • 220
xyzabc
  • 451
  • 1
  • 6
  • 13

1 Answers1

39

Use new RegExp(string) to build a regular expression dynamically. The literal /../ form cannot be used with dynamic content.

Make sure to have a valid pattern after building the string.

var len = 99;
var re = new RegExp(".(?=.{" + len + "})", "g");
var output = input.replace(re, "*")

Also see (and vote for dupe of):

user2864740
  • 60,010
  • 15
  • 145
  • 220