使用JavaScript,如何用省略号替换较长的文本序列?

时间:2019-10-31 13:34:54

标签: 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></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

如果单词多于5个,我想在<strong>标记的开头,结尾和中间添加省略号。

我设法开始并结束于:


      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(" ");

但是,我该怎么做所有中间部分?我的目标是使文本类似于:

    ... 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 ...

谢谢

1 个答案:

答案 0 :(得分:1)

  

但是,我该怎么做所有中间部分?

您可以使用正则表达式来匹配和替换中间部分,例如下面的演示代码。

INSERT INTO @Table
EXEC [dbo].[stored_procedured_name]

INSERT INTO #Table
EXEC [dbo].[stored_procedured_name]