You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript获取HTML注释内容?解决嵌套注释提取异常

修复JavaScript提取HTML注释内容的问题

你当前的代码用replaceAll全局替换所有<!--和-->,会误删注释内容里的相同字符串。要解决这个问题,只需要仅移除开头的<!--和结尾的-->,而不是全局替换所有匹配项。

方法一:正则表达式匹配首尾

利用正则的^(匹配字符串开头)和$(匹配字符串结尾)限定符,只替换首尾的目标标记:

function getContent(comment) {
  // 仅替换开头的<!--和结尾的-->
  return comment.replace(/^<!--/, '').replace(/-->$/, '');
}

// 测试用例
console.log(getContent("<!--hello world-->")); // 输出:"hello world"
console.log(getContent("<!--some <!--text-->")); // 输出:"some <!--text"

方法二:字符串截取(更直观)

通过startsWith和endsWith判断首尾标记,再用slice截取中间内容:

function getContent(comment) {
  let content = comment;
  // 移除开头标记
  if (content.startsWith('<!--')) {
    content = content.slice('<!--'.length);
  }
  // 移除结尾标记
  if (content.endsWith('-->')) {
    content = content.slice(0, -'-->'.length);
  }
  return content;
}

// 测试用例
console.log(getContent("<!--hello world-->")); // 输出:"hello world"
console.log(getContent("<!--some <!--text-->")); // 输出:"some <!--text"

这两种方法都能精准保留注释内容里的<!--字符串,不会误删。

内容的提问来源于stack exchange,提问作者c136

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:39:36