How to use user input as an Quantifier in Regex in JS?

牧云@^-^@ 提交于 2019-12-12 03:19:06

问题


My attempt was :

var re = new RegExp("\w{" + n + "}", "g");

But it didn't seems to work.

P.S. - I have searched several questions of Stackoverflow thinking it must have been asked before But I didn't find one, so I asked my question.


回答1:


The problem is that \ is not only the escape character in regex but also in JS strings. So when you create a regular expression from a string you need to escape it. This means that \w becomes "\\w" in a string and if you want to match a single \ it would even become "\\\\".

Instead of changing it to \\w you can also use . if you don't care about the characters or if the string was validated before.



来源:https://stackoverflow.com/questions/31640176/how-to-use-user-input-as-an-quantifier-in-regex-in-js

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