As the title says, I’ve got a string and I want to split into segments of n characters.
For example:
var str = 'abcdefghijkl';
after some magic with n=3, it will become
var arr = ['abc','def','ghi','jkl'];
Is there a way to do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Note: Use
{1,3}instead of just{3}to include the remainder for string lengths that aren’t a multiple of 3, e.g:A couple more subtleties:
.won’t capture those. Use/[\s\S]{1,3}/instead. (Thanks @Mike).match()will returnnullwhen you may be expecting an empty array. Protect against this by appending|| [].So you may end up with: