0

Based on the accepted answer in Split large string in n-size chunks in JavaScript I am trying to split a string from 1 to the number of characters it contains and push these into an array.

Here is my code:

function solve(s){
    var n = [];
     for (var i = 1; i <= s.length; i++) {
       n.push(s.match(/.{1,i}/g));
     }
    return n
  };

If I run solve("1341"); it returns [null, null, null, null]

However if I write my function without using the for loop, it does what I intended to do:

function solve(s){
    var n = [];
    n.push(s.match(/.{1,1}/g));
    n.push(s.match(/.{1,2}/g));
    n.push(s.match(/.{1,3}/g));
    n.push(s.match(/.{1,4}/g));
    return n
};

solve("1341"); returns [["1", "3", "4", "1"], ["13", "41"], ["134", "1"], ["1341"]]

Why is my code failing inside the for loop?

Kat
  • 69
  • 5

1 Answers1

1

In the loop i is a variable. When you use /.{1,i}/ you insert the letter i, and not the value of i to the expression. To create a regular expression that includes the value of i, create the string using string concatenation or template literals, and then use the RegExp constructor or factory on the string to convert it to the expression:

function solve(s) {
  var n = [];
  for (var i = 1; i <= s.length; i++) {
    n.push(s.match(RegExp('.{1,' + i + '}', 'g')));
  }
  return n
};

console.log(solve("1341"));
Ori Drori
  • 183,571
  • 29
  • 224
  • 209