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.

3 Answers 3

2

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

var re = new RegExp("%" + number + ":"  + "([yn]{5})", "g");
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
2
var matcher = new RegExp("(%" + number + ":)([yn]{5})", "g");

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

1 Comment

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

4 Comments

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.
Regular expressions are converted to strings when they're concanated with a string: "%" + /[yn]{5}/ > "%/[yn]{5}/".
@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, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.