使用JavaScript,我如何用省略号替换长文本序列?
我有一些文字,如:使用JavaScript,我如何用省略号替换长文本序列?,javascript,string,Javascript,String,我有一些文字,如: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. <strong class="ner" style="background-color: #2fbbab">nine months <small>datetime</small>&
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
<strong class="ner" style="background-color: #2fbbab">nine months <small>datetime</small></strong>
Urna condimentum mattis <strong class="ner" style="background-color: #2fbbab">December 20th <small>datetime</small></strong>
Euismod lacinia at quis risus sed vulputate odio ut
<strong class="ner" style="background-color: #2fbbab">December 1st<small>datetime</small></strong>
Euismod lacinia at quis risus sed vulputate odio ut
Lorem ipsum door sit amet,一位杰出的领导者,他是一位临时劳工和大股东。
九个月的日期时间
Urna调味品mattis12月20日日期时间
尤伊斯莫德·拉西尼亚(Euismod lacinia)在这座城市里被放逐了
12月1日星期三
尤伊斯莫德·拉西尼亚(Euismod lacinia)在这座城市里被放逐了
我想在开头、结尾和标签之间添加省略号,如果超过5个单词
我设法以以下内容开头和结尾:
let firstHighlightIndex = text.indexOf("<strong");
let lastHighlightIndex =
text.lastIndexOf("</strong>") + "</strong>".length;
let preText = text.substr(0, firstHighlightIndex).split(" ");
let postText = text.substr(lastHighlightIndex).split(" ");
text = text.slice(firstHighlightIndex, lastHighlightIndex);
if (preText.length > 5) {
preText = ["..."].concat(preText.slice(preText.length - 4));
}
if (postText.length > 5) {
postText = postText.slice(0, 4).concat("...");
}
text = preText.join(" ") + text + postText.join(" ");
让firstHighlightIndex=text.indexOf(“
然而,我怎样才能做所有的中间部分呢
您可以使用正则表达式来匹配和替换中间部分,如下面的演示代码
函数f(文本){
返回text.replace(
/(([^如果您能给出一些示例,说明它现在是如何显示的,以及您希望它是如何显示的,以及所需的输出,那会让您的问题更清楚一点为什么不使用css?文本溢出:省略号;@David因为他希望在开头、中间和结尾使用省略号,当有5个或更多单词时,它非常具体,css solution probably不会有用的here@CalvinNunes好的,我明白了
... et dolore magna aliqua.
<strong class="ner" style="background-color: #2fbbab">nine months <small>datetime</small></strong>
Urna condimentum mattis <strong class="ner" style="background-color: #2fbbab">December 20th <small>datetime</small></strong>
Euismod lacinia at ... vulputate odio ut
<strong class="ner" style="background-color: #2fbbab">December 1st<small>datetime</small></strong>
Euismod lacinia at ...