在JavaScript中将包含多个段落的字符串分成两部分
我有我想分手的字符串文本。我需要通过Facebook信使聊天API发送它,但该API只允许640个字符,而我的文本要长得多。我想要一个整齐的解决方案,我可以通过它发送文本。在JavaScript中将包含多个段落的字符串分成两部分
我是把包含多个段落的字符串拆分到最近的句号的两半。
如
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"
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向前迈出一步,然后回到最后一个走过去的字符串。 ,创建一个子串并重复。
什么是在上面的代码? –
@rohan sood对不起的错字... –
认为这是一个基础:
let slices = [], s;
for(let i = 0; s = a.slice(i * 640, (i+1) * 640); i++)
slices.push(s);
切片阵列将包含文本字符640块。但我们希望这是空间感知。我们需要在不超过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;
}
})
谢谢你,你是一个救世主:D –
你明白了。我刚刚意识到,如果任何单个句子的长度超过640个字符,您会发现奇怪的行为,所以请牢记这一点。 – Will
那么最后一句话呢?例如如果有1626个字符。只有第一个1280将被发送。其他人呢? –
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))
}
}
所以看640字和工作方式回来... – epascarello