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

javascript - concat variable in regexp pattern - Stack Overflow

programmeradmin0浏览0评论

I use this regex

str = "asd34rgr888gfd98";
var p = str.match(/\d{2}/);
alert(p[0]);

butI not understood how can use variable as quantificator, that is how write this:

 var number = 2;
 var p = str.match(/\d{number}/);

P.S. I see this page JavaScript regex pattern concatenate with variable but not understood how use example from these posts, in my case.

I use this regex

str = "asd34rgr888gfd98";
var p = str.match(/\d{2}/);
alert(p[0]);

butI not understood how can use variable as quantificator, that is how write this:

 var number = 2;
 var p = str.match(/\d{number}/);

P.S. I see this page JavaScript regex pattern concatenate with variable but not understood how use example from these posts, in my case.

Share Improve this question edited May 23, 2017 at 11:44 CommunityBot 11 silver badge asked Oct 25, 2012 at 12:48 Oto ShavadzeOto Shavadze 42.8k55 gold badges164 silver badges245 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 10

You need to build your regex as a string and pass it to the RegExp constructor:

var regexString = '\\d{' + number + '}';
var regex = new RegExp(regexString);
var p = str.match(regex);

Notice that when building a regex via a string, you need to add some extra escape characters to escape the string as well as the regex.

var number = "2"
var p = new RegExp("\\d{" + number + "}");

This should work:

var str = "asd34rgr888gfd98";
number = 3;
p = str.match(new RegExp('\\d{' + number + '}'));

alert(p[0]);
发布评论

评论列表(0)

  1. 暂无评论