chunk/split a string in Javascript without breaking words

后端 未结 4 2104
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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;
    }
    

提交回复
热议问题