Split string into array


/ Published in: JavaScript
Save to your folder(s)

I needed to break down a long string today and insert line breaks so I wrote this little function. You can use it to split a long string into chunks of a defined length and get them as an array or join them by a defined character (e.g. <br />). Have fun.


Copy this code and paste it in your HTML
  1. /**
  2.  * Splits string into chunks of defined lengths
  3.  * Returns an array by default or the joined version of the array if join_with is supplied
  4.  * @param string String to split
  5.  * @param number Size of the chunks to split the string into
  6.  * @param string Resulting array is joined into a string by this
  7.  * @return mixed Array with chunks or joined string
  8.  */
  9. function str_split(str, chunk_size, join_with)
  10. {
  11. var a_chunks = [], index = 0;
  12. do
  13. {
  14. a_chunks.push(str.slice(index, index+chunk_size));
  15. index += chunk_size;
  16. }
  17. while (index < str.length)
  18. return join_with ? a_chunks.join(join_with) : a_chunks;
  19. }
  20.  
  21.  
  22. // examples
  23. var str = 'thisisaverylongstringthatjustwontstopitgoesonandonandonandon';
  24. // split string into array
  25. var a = str_split(str, 5);
  26. // split string to fit a specified length in page
  27. document.write(str_split(str, 20, '<br />'));
  28. document.write('<br />');
  29. // split string (like a product identifier) to contain a new char
  30. document.write(str_split('203482034823329', 5, '-'));

URL: http://www.chlab.ch/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.