arrays - Javascript elegant way to split string into segments n characters long -


as title says, i've got string, , want split segments n characters long.

for example:

var str = 'abcdefghijkl'; 

after magic n=3, become

var arr = ['abc','def','ghi','jkl']; 

is there elegant way this?

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

note: use {1,3} instead of {3} include remainder string lengths aren't multiple of 3, e.g:

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


a couple more subtleties:

  1. if string may contain newlines (which want count character rather splitting string), . won't capture those. use /[\s\s]{1,3}/ instead. (thanks @mike).
  2. if string empty, match() return null when may expecting empty array. protect against appending || [].

so may end 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) || []);


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -