user7558372
user7558372

Reputation:

Split string at different size

I have a string like this one:

var s = 'Lorem ipsum dolor sit amet';

I want an array like this one:

var l = [3, 3, 3, 1, 2, 5, 4, 1, 2, 1];
var a = ['Lor', 'em ', 'ips', 'u', 'm ', 'dolor', ' sit', 'a', 'me', 't'];

The subdivisions do not have the same length.

I know a priori that I want the first element to have length 3 (Lor), the second 3 (em), the third 3 (ips), the fourth 1 (u), the fifth 2 (m), the sixth 5 (dolor), the seventh 4 (sit), the eighth 1 (a), the ninth 2 (me) and the tenth 1 (t).

How can I do?

Upvotes: 3

Views: 658

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386868

You could map the single length parts.

It works with a closure over the last position p

(p => i => string.slice(p, p += i))(0)
(p =>                             )(0) // call function with zero as p and return cb
      i => string.slice(p, p += i)     // callback for map

var lengths = [3, 3, 3, 1, 2, 5, 4, 1, 2, 1],
    string = 'Lorem ipsum dolor sit amet',
    result = lengths.map((p => i => string.slice(p, p += i))(0));
    
console.log(result);

Upvotes: 7

George
George

Reputation: 2422

This will do. but your question is confusing; the 3rd from last element is 2 in length, not 1.

var s = 'Lorem ipsum dolor sit amet';

var a = ['Lor', 'em ', 'ips', 'u', 'm ', 'dolor', ' sit', 'a', 'me', 't'];

var splitAt = [3, 3, 3, 1, 2, 5, 4, 2, 2, 1];

function splitByLengths(str, arr){
  var id = 0;
  var outputArr = [];
  arr.forEach(function(len){
    outputArr.push(str.slice(id, id+len));
    id += len;
 
  });
  return outputArr;
}
console.log(splitByLengths(s, splitAt));
console.log("as expected?", splitByLengths(s, splitAt) === a);

Upvotes: 2

Related Questions