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!
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!
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);
Try this:
> n = 3; text = 'abcd'; text.match(new RegExp(`.{1,${n}}`, 'g'));
[ 'abc', 'd' ]
>