jjzjj

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

coder 2024-05-07 原文

我试图将一大段文本拆分成多个字符串,每个字符串 148 个字符,同时避免切断单词。

我现在有这个,它正在拆分单词:

var length = shortData.new.length;

if (length < 160){

  outputString[0] = shortData.new;
  document.write(outputString[0]);

}


if (length > 160 && length < 308){

  outputString[0] = shortData.new.substring(0,148);
  outputString[1] = shortData.new.substring(148,length);    

  document.write(outputString[0]+"(txt4more..)");   
  document.write(outputString[1]);      

}


if (length > 308 && length < 468){


  outputString[0] = shortData.new.substring(0,148);
  outputString[1] = shortData.new.substring(148,308);   
  outputString[2] = shortData.new.substring(308,length);    

  document.write(outputString[0]+"(txt4more..)");   
  document.write(outputString[1]+"(txt4more..)");   
  document.write(outputString[2]);      

}


if (length > 468 && length < 641){


  outputString[0] = shortData.new.substring(0,148);
  outputString[1] = shortData.new.substring(148,308);   
  outputString[2] = shortData.new.substring(308,468);   
  outputString[3] = shortData.new.substring(468,length);    

  document.write(outputString[0]+"(txt4more..)");   
  document.write(outputString[1]+"(txt4more..)");   
  document.write(outputString[2]+"(txt4more..)");   
  document.write(outputString[3]);      

}

最佳答案

你可以使用这个函数,只要传入你的字符串和长度,它就会返回数组,比如:

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

函数:

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;
}

示例用法:

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);

输出:

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

关于javascript - JS : Splitting a long string into strings with char limit while avoiding splitting words,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7624713/

有关javascript - JS : Splitting a long string into strings with char limit while avoiding splitting words的更多相关文章

随机推荐