0

I have seen several similar questions on SO, but not exactly what I'm looking for.

I want to use a variable in my regEx so that when I call it, I can easily pass in a number.

Here's the hard coded regEx:

'mywonderfullString'.match(/.{1,3}/g)

Here's what I need:

'mywonderfullString'.match(/.{1,variableHERE}/g)

So when I call the regEx, I would do something like

'mywonderfullString'.match(/.{1,3}/g)

I've seen some examples using the replace regEx, but I can't seem to my example working.

Tushar
  • 78,625
  • 15
  • 134
  • 154
Ann
  • 97
  • 7

1 Answers1

2

You need to use RegExp constructor in-order to include variables inside regex.

var variableHERE = '3'
alert('mywonderfullString'.match(new RegExp(".{1," + variableHERE + "}", "g")))
Avinash Raj
  • 160,498
  • 22
  • 182
  • 229