【问题标题】:Truncate text to be less than 280 characters and then each word excluding "," to be less than 20 characters将文本截断为少于 280 个字符,然后将除“,”之外的每个单词截断为少于 20 个字符
【发布时间】:2020-05-03 13:53:57
【问题描述】:

这是我改变的js

#tag1 #tag2 #thisisareallyreallyrealyylongtag3

进入

tag1, tag2, thisisareallyreallyrealyylongtag3

它还将结果截断为 13 个单词..

  var str9 = document.getElementById("hashtagsplain").innerHTML;
  var resu9 = str9.replace(/^#|( #)/g, (_, m1) => m1 ? ", " : '');  
  var truncatethen = resu9.split(" ").splice(0,13).join(" ").slice(0, -1);
document.getElementById("x").innerHTML = truncatethen;

我现在需要补充的是,将整个文本截断为少于 280 个字符,然后将除“,”之外的每个单词(标签)的末尾截断为少于 20 个字符。

请问我要添加什么以及在哪里发生这种情况?

更新..

我已经通过添加排除了 280 个字符的限制部分

(/^(.{280}[^\s]*).*/, "$1")

现在我的代码看起来像这样..

  var str9 = document.getElementById("hashtagsplain").innerHTML;
  var resu9 = str9.replace(/^#|( #)/g, (_, m1) => m1 ? ", " : '');  
  var resu10 = resu9.replace(/^(.{280}[^\s]*).*/, "$1");    
  var truncatethen = resu10.split(" ").splice(0,13).join(" ").slice(0, -1);
document.getElementById("x").innerHTML = truncatethen;

我现在需要弄清楚如何将除“,”之外的每个单词截断为少于 20 个字符,所以

notalldisabilitiesarevisible, notalldisabilitiesarevisable, notalldisabilities

变成

notalldisabilitiesar, notalldisabilitiesar, notalldisabilities

【问题讨论】:

  • 您希望最终输出是什么?
  • 订单是什么?先去掉#,修剪成280个字符,然后把每个标签修剪成20个?
  • 考虑到最终输出,它将是一个逗号分隔的列表,并且对于订单.. 它应该首先删除主题标签并用逗号替换(就像我发布的代码一样)然后它应该截断结果减少到 13 个单词)接下来它应该将整个内容修剪为 280 个字符,最后它应该修剪每个标签的结尾(不包括,所以保留逗号),以便每个标签都在 20 个字符以下。跨度>
  • 我已经更新了我的操作,因为我已经能够计算出 280 个字符的限制部分,所以我现在需要计算出如何将除“,”之外的每个单词截断为小于 20人物。输入和预期输出的示例现在在更新的操作中。

标签: javascript html truncate


【解决方案1】:

slicemap 可以简化流程

var str9 = '#tag1 #tag2 #thisisareallyreallyrealyylongtag3 #notalldisabilitiesarevisible #notalldisabilitiesar #notalldisabilitiesar #notalldisabilities #tag1 #tag2 #thisisareallyreallyrealyylongtag3 #notalldisabilitiesarevisible #notalldisabilitiesar #notalldisabilitiesar #notalldisabilities #tag1 #tag2 #thisisareallyreallyrealyylongtag3 #notalldisabilitiesarevisible #notalldisabilitiesar #notalldisabilitiesar #notalldisabilities'

const textLength = 280;
const wordLength = 20;

var resu9 = str9.slice(1, textLength+1).replace(/#/g, ',');  
var truncatethen = resu9.split(',').map(str => str.slice(0, wordLength));    
truncatethen.forEach(str => console.log(str))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-03
    • 2021-12-09
    • 1970-01-01
    • 2022-10-07
    • 2012-01-29
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多