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

时间:2017-06-15 18:40:01

标签: 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"

3 个答案:

答案 0 :(得分:3)

将此视为基础:

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

切片数组将包含640个char文本块。但我们希望这是空间感知。我们需要找到一个尽可能接近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;
    }
})

答案 1 :(得分:0)

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步,然后回到最后一步。 ,创建一个子串并重复。

答案 2 :(得分:0)

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