Good day,
I would like to know if there is an easy way to chunk/split a string without breaking the words.
Eg:
var input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat, nisi nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
Should return an array like this if I break at 80 characters long:
var output = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin placerat, nisi",
"nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero",
"eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit",
"amet, consectetur adipiscing elit."];
I found that really nice piece of code:
//http://phpjs.org/functions/chunk_split:369
function chunk_split (body, chunklen, end) {
// Returns split line
//
// version: 1103.1210
// discuss at: http://phpjs.org/functions/chunk_split
// + original by: Paulo Freitas
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Theriault
// * example 1: chunk_split('Hello world!', 1, '*');
// * returns 1: 'H*e*l*l*o* *w*o*r*l*d*!*'
// * example 2: chunk_split('Hello world!', 10, '*');
// * returns 2: 'Hello worl*d!*'
chunklen = parseInt(chunklen, 10) || 76;
end = end || '\r\n';
if (chunklen < 1) {
return false;
}
return body.match(new RegExp(".{0," + chunklen + "}", "g")).join(end);
}
But I really doubt I can modify it so words aren't broken in half. Any tips?
Thank you!