I am attempting to create a tool that takes an input text and splits it into chunks of text at a certain # of characters. However, I need to make sure it does not split the
A short and simple way to split a string into chunks up to a certain length using a regexp:
const chunks = str.match(/.{1,154}(\s|$)/g);
some examples:
const str = 'the quick brown fox jumps over the lazy dog';
console.log(str.match(/.{1,10}(\s|$)/g))
console.log(str.match(/.{1,15}(\s|$)/g))
This works because quantifiers (in this case {1,154}
) are by default greedy and will attempt to match as many characters as they can. putting the (\s|$)
behind the .{1,154}
forces the match to terminate on a whitespace character or the end of the string. So .{1,154}(\s|$)
will match up to 154 characters followed by a whitespace character. The /g
modifier then makes it continue to match through the entire string.
To put this in the context of your function:
function splitText() {
"use strict";
var str = document.getElementById("user_input").value;
var chunks = str.match(/.{1,154}(\s|$)/g);
chunks.forEach(function (i,x) {
$("#display").append("
");
});
}
Note (as has been pointed out in the comments) that this code will fail if one of the words in the string is longer than the length of the chunks.