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">
Note: Regex can be created in two ways first one is regex literal and the second one is regex constructor method ( new RegExp() ). If we try to pass a variable to the regex literal pattern it won't work. The right way of doing it is by using a regular expression constructor new RegExp() .
%s symbol to put a variable in regex pattern We can also use the %s symbol to put a variable in the regex pattern.
A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.
\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With