简体   繁体   English

如何在正则表达式中使用变量

[英]How to use variable in regex

I have following RegExp and it is working fine 我正在关注RegExp,它工作正常

 var reg = new RegExp(/(.{1,4})/g);

But now i want to replace 4 with variable called limit then it is not working 但是现在我想用名为limit的变量替换4,那么它不起作用

 var reg = new RegExp("/(.{1,"+ limit +"})/g");

How could i use variable instead of fixed value in above RegExp? 我如何在上面的RegExp中使用变量而不是固定值?

Drop the / . 删除/ RegExp expects a string or a regex. RegExp需要字符串或正则表达式。 Then it takes a second parameter where you can specify the flags. 然后使用第二个参数,您可以在其中指定标志。

var reg = new RegExp("(.{1,"+ limit +"})", "g");

More here https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions 此处更多https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Regular_Expressions

这样(您不需要/ ):

 var reg = new RegExp(".{1,"+ limit +"}", "g");

Use it like this, 这样使用

var reg = new RegExp("(.{1,"+ limit +"}", "g");

The second parameter is used for options. 第二个参数用于选项。 And the pattern does not take any delimiter. 模式不带任何分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM