1

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?

8
  • Why RegExp, why not just use substr since you already start/ed positions of each substring Commented May 18, 2018 at 10:45
  • Thats possible too, I way just curious if this is something regex can handle Commented May 18, 2018 at 10:47
  • you can use multiple regex sub-groups in one regex Commented May 18, 2018 at 10:47
  • 1
    ^(........)(..............)(..........)(..........)(....)$ Commented May 18, 2018 at 10:51
  • 1
    @revo how fast can you tell number of characters in ".............." vs in ".{14}"? Commented May 18, 2018 at 11:14

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.