0

I want to split a string by a variable number of successive characters

splitBy4('XXXXXXXX') => ['XXXX', 'XXXX']

Before injecting the variable it worked all fine :

console.log('XXXXXXXX'.split(/(\w{4})/).filter(Boolean));
// outputs : ['XXXX', 'XXXX']
console.log('XXXXXXXX'.split(new RegExp(/(\w{4})/)).filter(Boolean));
// outputs : ['XXXX', 'XXXX']

But when I try to use the RegExp class + string representation (to inject my parameter), it fails :

console.log('XXXXXXXX'.split(new RegExp('(\w{4})')).filter(Boolean));
// outputs ['XXXXXXXX']

const nb = 4;
console.log('XXXXXXXX'.split(new RegExp('(\w{'+ nb +'})')).filter(Boolean));
// outputs ['XXXXXXXX']

What am I missing and how can I inject my parameter ? Thanks

Jscti
  • 14,096
  • 4
  • 62
  • 87

1 Answers1

-1
const nb = "4";
var myRegex = new RegExp('(\\w{' + nb + '})', 'g');
var myArray = myRegex.exec('XXXXXXXX');
console.log(myArray.toString());
Paul Oprea
  • 14
  • 1