/ Published in: JavaScript
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * 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, '-'));
URL: http://www.chlab.ch/