JS:将长字符串拆分为具有字符限制的字符串,同时避免拆分单词

时间:2011-10-02 05:03:15

标签: javascript regex sms

我正在尝试将大块文本分成多个字符串,每个字符串为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]);      

}

4 个答案:

答案 0 :(得分:26)

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

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

答案 1 :(得分:3)

您将需要填充一些字符串,以使它们具有您需要的字符数。

var lines= s.match(/(.{1,147}\s)\s*/g);

答案 2 :(得分:1)

你可以在长度为148的substr()上使用lastIndexOf()来找到中断原始字符串的位置,在长度为&gt;时删除并循环。 148,像这样:

var myText = "ad aenean adipiscing elit eget eleifend phasellus aenean lobortis vero venenatis ultricies eget iaculis ac neque nibh dignissim eleifend erat et in in justo sollicitudin mattis maecenas purus quis mi sed molestie integer magna non hendrerit nulla id neque augue suspendisse in in eget consectetuer et cubilia eu ullamcorper morbi elementum sed sed pharetra quam velit ante pellentesque eros nullam lobortis lorem fringilla libero elit nonummy purus sodales mauris sagittis praesent aenean in ut nullam ultricies quam aliquam arcu quisque semper lacinia lacinia sodales imperdiet ante venenatis suspendisse amet ante tellus nec nibh lorem in viverra magna cursus elit erat lobortis mattis purus pellentesque velit pellentesque dolor quam id mauris nibh pellentesque augue vel posuere aptent varius vivamus parturient hac ligula libero a varius sollicitudin sed dictumst morbi eros vestibulum donec purus turpis urna vel nisl quisque vulputate tristique non sed risus viverra varius tincidunt hendrerit ac dui mollis quam nunc suspendisse mattis volutpat vulputate integer ipsum cursus erat justo eu vestibulum sed blandit ac mi ligula montes sollicitudin vitae vel lacus imperdiet orci tincidunt sed imperdiet nunc vehicula pellentesque orci gravida diam non ut wisi sit et massa congue id scelerisque et mauris arcu nunc litora dignissim urna ea nullam magna felis duis pellentesque ultricies tincidunt vel pede fusce nunc sed interdum cursus wisi qui pulvinar wisi consectetuer fames sed hendrerit vitae velit viverra malesuada eu magna vehicula vivamus augue sagittis curabitur rutrum fringilla vivamus nisl enim eros elit vestibulum duis et duis erat sit auctor ac ipsum in et lacinia eu magna accumsan in nulla a sed massa maecenas ultricies duis dignissim sem augue id posuere lacus felis nisl quam ultricies urna dui curabitur morbi ante ut est eget tellus pulvinar mollis elementum tellus malesuada sollicitudin ligula fusce eget libero metus cras ligula felis nunc porttitor sit at";
var MAX_LENGTH = 148;

while (myText.length > MAX_LENGTH) {
    var s = myText.substr(0, MAX_LENGTH);
    var i = s.lastIndexOf(" ");
    alert(myText.substr(0, i));
    myText = myText.substr(i + 1, myText.length);
}
alert(myText);

答案 3 :(得分:0)

如果不考虑它,我会做这样的事情,而不是伪代码

if string length > 148
    for i=148;i<string length;i+148
        if character at i = space
            add substring(i-148 to i) to output[]
        else
            add substring(i-148 to lastindoxof space) to output[]
            set i to lastindoxof space + 1)
    if i-148 != string length
        add substring (i-148 to string length -1) to output[]