chunk/split a string in Javascript without breaking words

后端 未结 4 2093
小鲜肉
小鲜肉 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:31

    This builds on @steve's answer but will split the string respecting word break so that the string is never longer than the specified length. This works more like a normal word wrap.

    function chunkString(s, len)
    {
        var curr = len, prev = 0;
    
        output = [];
    
        while(s[curr]) {
          if(s[curr++] == ' ') {
            output.push(s.substring(prev,curr));
            prev = curr;
            curr += len;
          }
          else
          {
            var currReverse = curr;
            do {
                if(s.substring(currReverse - 1, currReverse) == ' ')
                {
                    output.push(s.substring(prev,currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while(currReverse > prev)
          }
        }
        output.push(s.substr(prev)); 
        return output;
    }
    
    0 讨论(0)
  • 2020-12-20 15:34

    Something like this?

    var n = 80;
    
    while (n) { 
        if (input[n++] == ' ') { 
            break;  
        } 
    }
    
    output = input.substring(0,n).split(' ');
    console.log(output);
    

    UPDATED

    Now that I re-read the question, here's an updated solution:

    var len = 80;
    var curr = len;
    var prev = 0;
    
    output = [];
    
    while (input[curr]) {
        if (input[curr++] == ' ') {
            output.push(input.substring(prev,curr));
            prev = curr;
            curr += len;
        }
    }
    output.push(input.substr(prev));  
    
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-12-20 15:39

    Thank to orourkedd, it iwas very useful. I just updated it with splitting.

    private chunkString(str, len) {
        let input = str.trim().split(' ');
        let [index, output] = [0, []]
        output[index] = '';
        input.forEach(word => {
            let temp = `${output[index]} ${word}`.trim()
            if (temp.length <= len) {
                output[index] = temp;
            } else {
                index++;
                output[index] = word;
            }
        })
        return output
    }
    
    0 讨论(0)
提交回复
热议问题