0

I have a simple regular expression:

str.match(/SK=([\w‌​\-]+)/i);

I would like the SK part to be dynamic so I can return the match for SK=, WP= etc...

So I'm looking for something like:

var attr = 'SK';
str.match(/' + attr  + '=([\w‌​\-]+)/i);

1 Answer 1

2

Use the constructor syntax to create your regex:

var myRegex = new RegExp(attr + "([\\w‌​\\-]+)","i");

and then:

str.match(myRegex);

See here (emphasis mine): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

The literal notation provides compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

The constructor of the regular expression object, for example, new RegExp("ab+c"), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but this returns null, I know the regex is valid because its been tested, but for some reason it doesn't work when using in RegExp...
@keeg: Yeah, you need to use double slash because it's now a string. So new RegExp(attr + "([\\w\\-]+)","i");. See this fiddle: jsfiddle.net/93Jb3
I had a feeling it was a slash issue! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.