fazlurr
2/5/2018 - 11:30 AM

Split String

Split string by length, and detect for newline. Origin: https://stackoverflow.com/a/7624821/1703124

function splitter (str, l) {
	var strs = [];
	while (str.length > l) {
		var newlinePosition = str.substring(0, l).lastIndexOf('\n');
		var isGotNewline = newlinePosition !== -1;
		// If there is a newline within the text range, then get the newline position
		var pos = isGotNewline ? newlinePosition : str.substring(0, l).lastIndexOf(' ');
		pos = pos <= 0 ? l : pos;
		strs.push(str.substring(0, pos));
		if (isGotNewline) {
			strs.push('');
		}
		var i = isGotNewline ? str.indexOf('\n', pos) + 1 : str.indexOf(' ', pos) + 1;
		if (i < pos || i > pos + l) i = pos;
		str = str.substring(i);
	}
	strs.push(str);
	return strs;
}