gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:55:20 25 4
gpt4 key购买 nike

我有想要分解的字符串文本。我需要通过 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);

切片数组将包含 640 个字符的文本 block 。但我们希望它具有空间意识。我们需要找到尽可能接近 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;
}
})

关于javascript - 在 JavaScript 中将包含多个段落的字符串分成两半,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44574672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com