JS: Splitting a long string into strings with char limit while avoiding splitting words

前端 未结 4 1881
情深已故
情深已故 2021-01-04 02:37

I am trying to take a large block of text and split it into multiple strings that are 148 characters each, while avoiding cutting off words.

I have this now, which

4条回答
  •  梦谈多话
    2021-01-04 03:19

    You can use this function, just pass in your string and the length and it will return the array, like:

    var outputString = splitter(shortData['new'], 148);
    

    The function:

    function splitter(str, l){
        var strs = [];
        while(str.length > l){
            var pos = str.substring(0, l).lastIndexOf(' ');
            pos = pos <= 0 ? l : pos;
            strs.push(str.substring(0, pos));
            var i = str.indexOf(' ', pos)+1;
            if(i < pos || i > pos+l)
                i = pos;
            str = str.substring(i);
        }
        strs.push(str);
        return strs;
    }
    

    Example usage:

    splitter("This is a string with several characters.\
    120 to be precise I want to split it into substrings of length twenty or less.", 20);
    

    Outputs:

    ["This is a string","with several","characters. 120 to",
    "be precise I want","to split it into","substrings of",
    "length twenty or","less."]
    

提交回复
热议问题