0

I have a simple regular expression inside a match function like this:

text.match(/.{1,20}/g);

Is it possible to replace the 20 with a dynamic variable?

Thanks a lot!

user2028856
  • 2,911
  • 8
  • 41
  • 68

2 Answers2

1

Use the RegExp constructor, not the literal. That allows you to do string concatenation or interpolation as you please:

let n = 20;
let r = new RegExp(".{1," + n + "}", "g");

text.match(r);
weltschmerz
  • 12,936
  • 10
  • 60
  • 110
-1

Try this:

> n = 3; text = 'abcd'; text.match(new RegExp(`.{1,${n}}`, 'g'));
[ 'abc', 'd' ]
> 
yingted
  • 9,516
  • 4
  • 22
  • 15