Oto Shavadze
Oto Shavadze

Reputation: 42753

concat variable in regexp pattern

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.

Upvotes: 4

Views: 7359

Answers (3)

Matti Mehtonen
Matti Mehtonen

Reputation: 1705

This should work:

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

alert(p[0]);

Upvotes: 4

jbabey
jbabey

Reputation: 46647

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.

Upvotes: 10

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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

Upvotes: 4

Related Questions