【问题标题】:Replace contents of HTML comments, but not the comments themselves [duplicate]替换 HTML 注释的内容,而不是注释本身 [重复]
【发布时间】:2021-07-23 23:27:12
【问题描述】:

我有以下markdown文件,其中包含一系列HTML样式的cmets:

hello this is my file

<!-- START COMMENT -->
<!-- END COMMENT -->

the rest of the file

有时评论标签是空的,而其他时候它们里面会有内容:

hello this is my file

<!-- START COMMENT -->
some
content
here
<!-- END COMMENT -->

the rest of the file

我正在尝试替换标签的内容,但保持标签完好无损,以便它们仍然围绕内容。我尝试了以下正则表达式,但它似乎也替换了标签,这不是我需要的:

data = data.replace(
  /<!-- START COMMENT -->[\s\S]*?<!-- END COMMENT -->/g,
  generatePlaceholders(response)
)

如何调整我的正则表达式,使其替换内容?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您可以使用替换文本重新插入 cmets。 如果您将&lt;!-- START COMMENT --&gt;&lt;!-- END COMMENT --&gt; 放在匹配组中,您可以再次引用它们并再次插入它们($1$2 是开始和结束),同时替换里面的内容。

    const p = document.getElementById('content').innerHTML;
    const replacement = 'new content';
    
    console.log(p.replace(/(<!-- START COMMENT -->)[\s\S]*?(<!-- END COMMENT -->)/, `$1${replacement}$2`));
    <div id="content">
    hello this is my file
    
    <!-- START COMMENT -->
    some
    content
    here
    <!-- END COMMENT -->
    
    the rest of the file
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2010-12-18
      • 2012-12-04
      • 2014-08-14
      • 2019-02-23
      • 2015-08-07
      相关资源
      最近更新 更多