问题
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