Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to splits the line at x characters or less, and only at a space (" ")?

Tags:

javascript

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));
       }
}
like image 577
don Avatar asked Jan 04 '23 06:01

don


1 Answers

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);
like image 92
Faly Avatar answered Jan 16 '23 20:01

Faly