I'm creating program which splits the line at x characters and only at a space (" ").
Input paragraph:
There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so
Input split characters: 30
Now I am getting output like this:
var textArray = ["There was no possibility of ta","king a walk that day. We had b","een wandering, indeed, in the ","leafless shrubbery an hour in ","the morning; but since dinner ","(Mrs. Reed, when there was no ","company, dined early) the cold"," winter wind had brought with ","it clouds so sombre, and a rai","n so "]`
But I want only splits at the space (). It splits at the last space before the number of characters specified.
I want output like this:
var textArray = ["There was no possibility of", "taking a walk that day. We", "had been wandering, indeed, in", "the leafless shrubbery an hour", "in the morning; but since", "dinner (Mrs. Reed, when there", "was no company, dined early)", "the cold winter wind had", "brought with it clouds so", "sombre, and a rain so", "penetrating, that further", "out-door exercise was now out", "of the question."]`
I tried this code :
function textToArray() {
var str = document.getElementById('stringg').value;
var strArr = [];
var count = parseInt(document.getElementById('numberOfWords').value, 10) || 1;
for (var i = 0; i < str.length; i = i + count) {
var j = i + count;
strArr.push(str.substring(i,j));
}
}
You can use array.reduce:
var str = "There was no possibility of taking a walk that day. We had been wandering, indeed, in the leafless shrubbery an hour in the morning; but since dinner (Mrs. Reed, when there was no company, dined early) the cold winter wind had brought with it clouds so sombre, and a rain so";
str = str.split(' ').reduce((m, o) => {
var last = m[m.length - 1];
if (last && last.length + o.length < 30) {
m[m.length - 1] = `${last} ${o}`;
} else {
m.push(o);
}
return m;
}, []);
console.log(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With