Return to Snippet

Revision: 25369
at March 29, 2010 07:10 by chlab


Initial Code
/**
 * Splits string into chunks of defined lengths
 * Returns an array by default or the joined version of the array if join_with is supplied
 * @param   string   String to split
 * @param   number   Size of the chunks to split the string into
 * @param   string   Resulting array is joined into a string by this
 * @return  mixed    Array with chunks or joined string
 */
function str_split(str, chunk_size, join_with)
{
  var a_chunks = [], index = 0;
  do 
  {
    a_chunks.push(str.slice(index, index+chunk_size));
    index += chunk_size;  
  }
  while (index < str.length)
  return join_with ? a_chunks.join(join_with) : a_chunks;
}


// examples
var str = 'thisisaverylongstringthatjustwontstopitgoesonandonandonandon';
// split string into array
var a = str_split(str, 5);
// split string to fit a specified length in page
document.write(str_split(str, 20, '<br />'));
document.write('<br />');
// split string (like a product identifier) to contain a new char
document.write(str_split('203482034823329', 5, '-'));

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

Initial Description
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. &lt;br /&gt;). Have fun.

Initial Title
Split string into array

Initial Tags
javascript, array

Initial Language
JavaScript