chunk/split a string in Javascript without breaking words

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

提交回复
热议问题