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

xn1cxnb4  于 2023-03-20  发布在  其他
关注(0)|答案(5)|浏览(161)

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

}
ecr0jaav

ecr0jaav1#

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

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

lb3vh1jj2#

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

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

fjnneemd3#

你可以在长度为148的substr()上使用lastIndexOf()来找到在哪里打断原始字符串,然后删除它,并在长度大于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);
8ftvxx2r

8ftvxx2r4#

不用想太多,我会做类似这样的事情,只是不是用伪代码

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[]
czfnxgou

czfnxgou5#

不得不为我的项目想出类似的东西。

const addLineToResult = ({ content, result }) => {
    result.push(content);
};

const handleReadLine = ({ fullString, config, limit }) => {
    const start = config.counter;
    const end = config.counter + limit + 1;
    const result = config.result;

    for (let i = start; i < end; i++) {
        config.counter++;

        if (fullString[i] === '\n' || !fullString[i]) {
            addLineToResult({ content: fullString.slice(start, i).trim(), result });
            break;
        } else if (i === end - 1) {
            if (fullString[i] !== ' ') {
                for (let j = i; j >= start; j--) {
                    if (fullString[j] === ' ') {
                        addLineToResult({ content: fullString.slice(start, j).trim(), result });
                        config.counter = j;

                        break;
                    }
                }
            } else {
                addLineToResult({ content: fullString.slice(start, end).trim(), result });
            }
        }
    }
};

const handleGetClampedString = ({ fullString, limit }) => {
    const config = {
        counter: 0,
        result: [],
    };

    do {
        handleReadLine({ fullString, config, limit });
    } while (config.counter <= fullString.length);

    return config.result;
};

console.log(handleGetClampedString({ fullString: `This is a very long string that excceds the limit of characters or symbols in each line.\nIt needs to be split and then sent to an array.`, limit: 40 }));

运行它,

handleGetClampedString({ fullString: `<your string>`, limit: 20 });

相关问题