JS:将长字符串拆分为具有字符限制的字符串,同时避免拆分单词 [英] JS: Splitting a long string into strings with char limit while avoiding splitting words

查看:185
本文介绍了JS:将长字符串拆分为具有字符限制的字符串,同时避免拆分单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将大块文本分成多个字符串,每个字符串为148个字符,同时避免切断单词。

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 is splitting words:

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

}


推荐答案

你可以使用此函数,只需传入您的字符串和长度,它将返回数组,如:

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

功能:

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."]

这篇关于JS:将长字符串拆分为具有字符限制的字符串,同时避免拆分单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆