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

javascript - Using a string variable as regular expression - Stack Overflow

programmeradmin1浏览0评论

In JavaScript, we append /g to an unquoted string to denote a regular expression.

What if I have a string in a variable and want to use it as a regular expression?

Is this possible? If so, can anyone show me some example code?

Thanks.

In JavaScript, we append /g to an unquoted string to denote a regular expression.

What if I have a string in a variable and want to use it as a regular expression?

Is this possible? If so, can anyone show me some example code?

Thanks.

Share Improve this question asked Jan 24, 2011 at 20:46 Tom TuckerTom Tucker 11.9k23 gold badges95 silver badges131 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Use this:

new RegExp("your regex here", "modifiers");

And notice that /g is not the delimiter for a regex, it is global modifier. A regex looks like this: /your regex here/modifiers. modifiers can be a bination of g, i and m. They are all explained here: http://www.regular-expressions.info/javascript.html

/g is a flag denoting global ( match all instances of the regex ), it doesn't denote a regular expression but is simply a flag.

If you want a dynamic regex use new RegExp. Usage here: https://developer.mozilla/en/JavaScript/Reference/Global_Objects/RegExp

Thanks, Gabi, you helpmed a lot. However, I had to put the regexp part (the variable part) without quotes to make it work:

new RegExp(yourRegExp, "modifiers").

I hope this helps someone.

发布评论

评论列表(0)

  1. 暂无评论