chunk/split a string in Javascript without breaking words

后端 未结 4 2103
小鲜肉
小鲜肉 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: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));  
    

提交回复
热议问题