var txtpattern = '/[a-z]+/';
var regex = new RegExp(txtpattern);
var result = txtstring.match(regex); //returns null
var result = txtstring.match(/[a-z]+/); //returns some value
My query is, Is there any way to set the dynamic pattern in match arguments?
var txtpattern = '/[a-z]+/';
var regex = new RegExp(txtpattern);
var result = txtstring.match(regex); //returns null
var result = txtstring.match(/[a-z]+/); //returns some value
My query is, Is there any way to set the dynamic pattern in match arguments?
Share Improve this question edited Jan 4, 2012 at 16:35 Pankaj asked Jan 4, 2012 at 16:26 PankajPankaj 10.1k39 gold badges151 silver badges297 bronze badges 2-
2
Yes, exactly how you did it. I'd assume the expression in
txtpattern
is not correct. Maybe it includes the/
, which are not part of the expression. You have to omit them. Or you did not escape the\
properly. But without seeing the value oftextpattern
, these are just guesses. – Felix Kling Commented Jan 4, 2012 at 16:29 -
Regarding your update: In the first case, your expression is
/[a-z]+/
, in the second it is[a-z]+
./.../
are denoting a regex literal, much like[...]
denotes an array literal, meaning, they are not part of your expression. – Felix Kling Commented Jan 4, 2012 at 16:43
1 Answer
Reset to default 7When using new Regex()
, you need to remove the start and end /
characters, like so:
var txtpattern = '[a-z]+';
var regex = new RegExp(txtpattern);
var result = txtstring.match(regex);