开发者

javascript syntax for regex using variable as pattern

开发者 https://www.devze.com 2023-04-12 04:21 出处:网络
I have a variable patt with a dynamic numerical value var patt = \"%\"+number+\":\"; What is the regex syntax for 开发者_JAVA技巧using it in the test() method?

I have a variable patt with a dynamic numerical value

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

What is the regex syntax for 开发者_JAVA技巧using it in the test() method?

I have been using this format

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

TIA


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


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


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消