marchello
marchello

Reputation: 2136

Split string with Javascript RegExp based on different character lengths

I have a string that looks like this:

"12345678ABCDEFGHIJKLMN2018/05/202018/05/30ABCD"

I want to split it based on n-sized lengths: 8 chars, 14 chars, 10 chars, 10 chars, 4 chars

So it would look like this:

12345678 (8 chars)

ABCDEFGHIJKLMN (14 chars)

2018/05/20 (10 chars)

2018/05/30 (10 chars)

ABCD (4 chars)

I know I could do this way: /(.{8})/ then split the string and continue /(.{14})/ and so on... But I was wondering if it is possible with on RegExp?

Upvotes: 1

Views: 64

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could match the length' with groups.

The result of match contains the full match and the groups. To get only the groups, this solution takes a destructuring assignment to a sparse array with rest parameters ... for getting an array without the first element.

var string = "12345678ABCDEFGHIJKLMN2018/05/202018/05/30ABCD",
    [, ...result] = string.match(/^(.{8})(.{14})(.{10})(.{10})(.{4})$/);
    
console.log(result);

Upvotes: 2

Related Questions