如何将Javascript字符串拆分为少于140个字符的句子

How can I split a Javascript string into sentences that are less than 140 characters?

本文关键字:140个 字符 句子 Javascript 字符串 拆分      更新时间:2023-09-26

我在Javascript环境中使用一个字符串,我最终想通过Twitter机器人发推。问题是,有时这个字符串是两个短句,有时是几个很长的句子。

我使用的字符串示例:

做空:

"白富。没有那么多废话">

长:

"很多废话。太多了。这个foo不可能放在一条推特上。此推文中的字符需要制作成多个推文。事实上,共有189个字符">

我还加上了开头和结尾,所以它最终看起来像这样:

做空:

"今天:白富。没有那么多废话#标签";

我想把长度超过140的字符串分成几个推文。

长推特1:

"今天:很多废话。太多了。这个foo不可能放在一条推特上#标签";

长推特2:

"此推文中的字符需要制作成多个推文。事实上,共有189个字符#标签";

在我看来,我可以用string.split()将整个字符串组合成一组句子,并循环使用它们来构建每条推文,也可以使用Regex将长字符串选择并拆分为多个大小刚好为140个字符的字符串。

哪种方法更有效?我认为这将是Regex选项。我将如何着手实施该解决方案?

一种天真但简单的方法是使用类似的正则表达式

/.{1,140}'./g

示例:

text = "Lots of blah foo. So many foo. There is a no way that this foo would fit in one tweet. The characters in this tweet need to be made into a multiple tweets. In fact, there are 189 characters."
m = text.match(/.{1,140}'./g)
for (let tweet of m)
    console.log(tweet, tweet.length)

var arr = [];
var str = "Lots of blah foo. So many foo. There is a no way that this foo would fit in one tweet. The characters in this tweet need to be made into a multiple tweets. In fact, there are 189 characters.";
arr.push(str.substring(0, 140));
arr.push(str.substring(140));