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
  • 3,063
  • 8
  • 44
  • 71

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);
Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
-1

Try this:

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