passing variable to javascript regexp: combination of variable and regexp pattern

匿名 (未验证) 提交于 2019-12-03 09:06:55

问题:

I need to pass variable into RegExp

form = form.replace(/someVar\_\d+/g, someVar+"_"+num) 

I read this question, but there is not a combination of regular expression (like \d+) and a string variable:

How do you use a variable in a regular expression?

And I can use eval here, but I want to avoid it

回答1:

You're looking for almost the same thing the question shows:

var r = new RegExp(someVar + "_\\d+","g"); 

Two minor notes:

  • You may want to escape regexp meta-characters that may be present in someVar.
  • Note "\\d+" is a string, so you have to escape the backslash.


回答2:

I'm assuming you are asking how to escape your string so it isn't interpreted as regex.

http://simonwillison.net/2006/Jan/20/escape/ should be what you are looking for then.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!