Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable inside a RegEx pattern? [duplicate]

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">
like image 631
xyzabc Avatar asked Aug 02 '17 04:08

xyzabc


People also ask

Can I use variable in regex?

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() .

How do you put a variable inside a regular expression?

%s symbol to put a variable in regex pattern We can also use the %s symbol to put a variable in the regex pattern.

How do you repeat in regex?

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.

What does \\ mean in regex?

\\. 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 \.


1 Answers

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):

  • How do you use a variable in a regular expression?
like image 171
user2864740 Avatar answered Oct 29 '22 04:10

user2864740