当撰写的推文超过 140 个字符时,如何修剪它

How do I trim down a composed Tweet when it exceeds 140 charcters?

本文关键字:何修剪 修剪 字符 文超过      更新时间:2023-09-26

我有一个推文函数,可以删除@-提及,并且在以下情况下不会发推文:1)如果问题与答案不同,2) 如果撰写的推文超过 140 个字符,并且3)如果推文可能敏感。

工作正常,但如果它的长度超过 140,我宁愿修剪组合answer。理想情况下,我想砍掉除前 137 个字符以外的所有字符并添加"..."我不确定最好的方法是什么。

如何减少这条推文?

这是当前代码:

function(tweet) {
var question = tweet.txt;
var answer = tweet.txt + "some text";
if(question !== answer && answer.length < 140 && !tweet.possibly_sensitive) {
       answer = answer.replace(/@/g, "."); //removes @-mentions.
       return { id_str: tweet.id_str, text: answer };
     }
}

您可以使用 JavaScript 中的字符串对象提供的slice()删除答案字符串的末尾。

// returns a new answer string containing the first 137 characters
// with '...' tacked onto the end
answer = answer.slice(0,137) + '...'; `