Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


1 Answers

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);
like image 87
Nina Scholz Avatar answered Mar 27 '26 14:03

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!