繁体   English   中英

在JavaScript中将包含多个段落的字符串分成两半

[英]Breaking a string containing multiple paragraphs into two halves in JavaScript

我有要拆分的字符串文本。 我需要通过Facebook Messenger聊天API发送该消息,但该API仅允许640个字符,而且我的文本更长。 我想要一个整洁的解决方案,可以用来发送文本。

我要把包含多个段落的字符串分成两半,最接近的句号。

例如

var str = "This is paragraph one. I need Mr. Sam to my errand. The errand must be done by him. He is the best.

Mr. Sharma is also good. Btw this is the second paragraph. I think you get my point. Sentence again. Sentence again.

Paragraph three is started. I am writing so much now. This is fun. Thanks";

//Expected output

var half1 = "This is paragraph one. I need Mr. Sam to my errand. The errand must be done by him. He is the best.

Mr. Sharma is also good. Btw this is the second paragraph."

var half2 = "I think you get my point. Sentence again. Sentence again.

Paragraph three is started. I am writing so much now. This is fun. Thanks"

以此为基础:

let slices = [], s;
for(let i = 0; s = a.slice(i * 640, (i+1) *  640); i++)
    slices.push(s);

slices数组将包含640个字符的文本块。 但是我们希望这是空间意识的。 我们需要找到一个尽可能接近该640标记的句子结尾,而不会越过它。 如果我们想了解空间,它将使我们的生活更容易处理整个句子而不是字符:

// EDIT: Now, if a sentence is less than 640 chars, it will be stored as a whole in sentences
// Otherwise, it will be stored in sequential 640-char chunks with the last chunk being up to 640 chars and containing the period.
// This tweak also fixes the periods being stripped
let sentences = str.match(/([^.]{0,639}\.|[^.]{0,640})/g)

这是该讨厌的正则表达式的快速演示: https : //jsfiddle.net/w6dh8x7r

现在,我们可以一次创建多达640个字符的结果。

let result = ''
sentences.forEach(sentence=> {
    if((result + sentence).length <= 640) result += sentence;
    else {
        API.send(result);
        // EDIT: realized sentence would be skipped so changed '' to sentence
        result = sentence;
    }
})
var results=[];
var start=0;
for(var i=640;i<str.length;i+=640){//jump to max
 while(str[i]!=="."&&i) i--;//go back to .
  if(start===i) throw new Error("impossible str!");
  results.push(str.substr(start,i-start));//substr to result
  start=i+1;//set next start
 }
}
//add last one
results.push(str.substr(start));

您可以向前迈出640步,然后回到最后一步,以遍历整个字符串。 ,创建一个子字符串并重复。

    var txt = 'This is paragraph one. I need Mr. Sam to my errand. The errand must be done by him. He is the best. Mr. Sharma is also good. Btw this is the second paragraph. I think you get my point. Sentence again. Sentence again. Paragraph three is started. I am writing so much now. This is fun. Thanks'
    var p = []
    splitValue(txt, index);

    function splitValue(text)
    {
        var paragraphlength = 40;
        if (text.length > paragraphlength) 
        {
            var newtext = text.substring(0, paragraphlength);
            p.push(newtext)
            splitValue(text.substring(paragraphlength + 1, text.length))
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM