Jamex
Jamex

Reputation: 1222

javascript syntax for regex using variable as pattern

I have a variable patt with a dynamic numerical value

var patt = "%"+number+":";

What is the regex syntax for using it in the test() method?

I have been using this format

var patt=/testing/g;
var found = patt.test(textinput);

TIA

Upvotes: 36

Views: 31357

Answers (4)

Daniil Iaitskov
Daniil Iaitskov

Reputation: 6039

These days many people enjoy ES6 syntax with babel. If this is your case then there is an option without string concatenation:

const matcher = new RegExp(`%${num_to_match}:`, "g");

Upvotes: 3

MicronXD
MicronXD

Reputation: 2220

Yeah, you pretty much had it. You just needed to pass your regex string into the RegExp constructor. You can then call its test() function.

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

Hope that helps :)

Upvotes: 36

Gopherkhan
Gopherkhan

Reputation: 4342

You have to build the regex using a regex object, rather than the regex literal.

From your question, I'm not exactly sure what your matching criteria is, but if you want to match the number along with the '%' and ':' markers, you'd do something like the following:

var matcher = new RegExp("%" + num_to_match + ":", "g");

You can read up more here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

Upvotes: 8

Jason Gennaro
Jason Gennaro

Reputation: 34855

You're on the right track

var testVar = '%3:';

var num = 3;

var patt = '%' + num + ':';

var result = patt.match(testVar);

alert(result);

Example: http://jsfiddle.net/jasongennaro/ygfQ8/2/

You should not use number. Although it is not a reserved word, it is one of the predefined class/object names.

And your pattern is fine without turning it into a regex literal.

Upvotes: 5

Related Questions