1

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.

Jamex
  • 1,164
  • 5
  • 22
  • 34

3 Answers3

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

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

Amber
  • 507,862
  • 82
  • 626
  • 550
  • Thanks Amber, I had something similar to yours, and I guess it did work, I just have something else that did not work. Thanks for the help. – Jamex Oct 16 '11 at 17:55
2

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

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Thanks Rob W, I did something similar to this last night, it turns out that it did work, I just have something else that does not work. – Jamex Oct 16 '11 at 17:53
  • Regular expressions are converted to strings when they're concanated with a string: `"%" + /[yn]{5}/` > `"%/[yn]{5}/"`. – Rob W Oct 16 '11 at 17:57
  • @Jamex In your first RegExp, you were using `dynamicnumber`. In the second RegExp, however, you're using `number`. Are you sure that this is correct? – Rob W Oct 16 '11 at 18:00
  • @Rob W, I just forgot to change the text when I posted, but your suggestion does work. I just need to figure out why I can't replace the pattern in my string, probably something simple. Thanks. – Jamex Oct 16 '11 at 18:33
2

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

var re = new RegExp("%" + number + ":"  + "([yn]{5})", "g");
FailedDev
  • 26,680
  • 9
  • 53
  • 73
  • Thanks Failed, this is exactly what I did last night (or I thought I did), but it did not work. But now I have an alert statement, and it does return the match as 'true', so it does work, but I guess my replace code does not replace. – Jamex Oct 16 '11 at 17:51
  • I will try to figure it out first since I now have confirmation that the pattern does work. It is probably something really simple that I missed due to trying to write codes at 2-3am. Thank you for your help. – Jamex Oct 16 '11 at 18:37