0

For example, I have a string:

var s = "ABCDEFGHIJKLMN";

I would like to get an array of substrings whose length is 1 to 5.

The result I expect is:

["ABCDE", "FGHIJ", "KLMN"]

I tried to get the result via regexp. Here is my code:

var s = "ABCDEFGHIJKLMN";
var result = s.match(/(.{1,5})+/)

But I can only get the last match of the group instead of all of them:

result[1];
"KLMN"

2 Answers 2

2

Use split with a capturing group, and remove the empty strings:

var s = "ABCDEFGHIJKLMN";
var result = s.split(/(.{1,5})/).filter(e => e);
console.log(result);

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

2 Comments

Didn't know split() function can accept regexp as argument. Thanks!
No problem @krave, always glad to help.
1

Add a "g" to the end of the pattern:

var s = "ABCDEFGHIJKLMN";
var result = s.match(/.{1,5}/g)
console.log(result)

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.