javascriptarraysstringsplit

How can I split a string into segments of n characters?


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?


Solution

  • var str = 'abcdefghijkl';
    console.log(str.match(/.{1,3}/g));

    Note: Use {1,3} instead of just {3} to include the remainder for string lengths that aren't a multiple of 3, e.g:

    console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]


    A couple more subtleties:

    1. If your string may contain newlines (which you want to count as a character rather than splitting the string), then the . won't capture those. Use /[\s\S]{1,3}/ instead. (Thanks @Mike).
    2. If your string is empty, then match() will return null when you may be expecting an empty array. Protect against this by appending || [].

    So you may end up with:

    var str = 'abcdef \t\r\nghijkl';
    var parts = str.match(/[\s\S]{1,3}/g) || [];
    console.log(parts);
    
    console.log(''.match(/[\s\S]{1,3}/g) || []);