chunk/split a string in Javascript without breaking words

后端 未结 4 2095
小鲜肉
小鲜肉 2020-12-20 14:42

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 dolo         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 15:38

    Here's some brute force code that will do it:

    function splitIntoLines(input, len) {
        var i;
        var output = [];
        var lineSoFar = "";
        var temp;
        var words = input.split(' ');
        for (i = 0; i < words.length;) {
            // check if adding this word would exceed the len
            temp = addWordOntoLine(lineSoFar, words[i]);
            if (temp.length > len) {
                if (lineSoFar.length == 0) {
                    lineSoFar = temp;     // force to put at least one word in each line
                    i++;                  // skip past this word now
                }
                output.push(lineSoFar);   // put line into output
                lineSoFar = "";           // init back to empty
            } else {
                lineSoFar = temp;         // take the new word
                i++;                      // skip past this word now
            }
        }
        if (lineSoFar.length > 0) {
            output.push(lineSoFar);
        }
        return(output);
    }
    
    function addWordOntoLine(line, word) {
        if (line.length != 0) {
            line += " ";
        }
        return(line += word);
    }
    

    If this routine encounters a single word longer than the desired line length, it will put it on a line by itself and will not break it up.

    You can play with it here: http://jsfiddle.net/jfriend00/fbaLe/

提交回复
热议问题