javascript find and replace a dynamic pattern in a

2019-06-03 13:02发布

问题:

I have a dynamic pattern that I have been using the code below to find

var matcher = new RegExp("%" + dynamicnumber + ":", "g");
var found = matcher.test(textinput);

I need the pattern to have a new requirement, which is to include an additional trailing 5 characters of either y or n. And then delete it or replace it with a '' (nothing).

I tried this syntax for the pattern, but obviously it does not work.

var matcher = new RegExp("%" + dynamicnumber + ":"  + /([yn]{5})/, "g");

Any tip is appreciated

TIA.

回答1:

You should only pass the regex string into the RegExp c'tor :

var re = new RegExp("%" + number + ":"  + "([yn]{5})", "g");


回答2:

var matcher = new RegExp("(%" + number + ":)([yn]{5})", "g");

Then replace it with the contents of the first capture group.



回答3:

Use quotes instead of slashes:

var matcher = new RegExp("%" + number + ":([yn]{5})", "g");

Also, make sure that dynamicnumber or number are valid RegExps. special characters have to be prefixed by a double slash, \\, a literal double slash has to be written as four slashes: \\\\.