最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - set dynamic pattern in Regexp - Stack Overflow

programmeradmin3浏览0评论
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 of textpattern, 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
Add a ment  | 

1 Answer 1

Reset to default 7

When 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);
发布评论

评论列表(0)

  1. 暂无评论