How can I set a character limit of 100 without splitting words?

前端 未结 1 501
耶瑟儿~
耶瑟儿~ 2021-01-07 02:44

I want to cut a string every 100 characters without cutting up words.

var TmpArray=[];
var str = \'this string will be cut up after every 100 characters but          


        
相关标签:
1条回答
  • 2021-01-07 03:14

    Interesting question. I will propose one more implementation of how you can use just array methods, combination of split + reduce:

    var str = 'This example of the string that we want to split by spaces only making sure that individual chunk is less or equal to specified number.';
    
    // Split by spaces
    str.split(/\s+/)
    
    // Then join words so that each string section is less then 40
    .reduce(function(prev, curr) {
        if (prev.length && (prev[prev.length - 1] + ' ' + curr).length <= 40) {
            prev[prev.length - 1] += ' ' + curr;
        }
        else {
            prev.push(curr);
        }
        return prev;
    }, [])
    
    // Print for testting
    .forEach(function(str) {
        console.log(str + ' ' + str.length);
    });

    For this example I set maximum length of 40 characters.

    Output:

    This example of the string that we want 39
    to split by spaces only making sure that 40
    individual chunk is less or equal to 36
    specified number. 17
    

    One more demo: http://jsfiddle.net/9tgo6n1t/

    0 讨论(0)
提交回复
热议问题