36

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

4 Answers 4

36

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 :)

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

1 Comment

Be careful when you want to use a special character that is also a string escape character like, \s, you will need to double-escape some special characters, Eg: new RegExp(`\\s*${var}`, 'g') to match all whitespace up to a variable.
8

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

Comments

5

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.

2 Comments

Your example works because you have MooTools loaded. A String doesn't normally have a .test() method. And number is not a reserved word.
@Ӫ_._Ӫ You're so right!! Thinking in frameworks too much. I've edited to remove test() for match(). Thanks for the catch. Also, you're right about number not being a reserved word. Edited that too to be more clear. Typing to quickly without double-checking my facts. ;-)
3

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");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.