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

JavaScript中Replace误删全部HTML标签,如何仅移除<mark>标签?

解决仅移除标签保留其他HTML结构的问题

问题根源

你当前代码里使用了.text()方法,这个方法会提取元素内的纯文本内容,自动丢弃所有HTML标签(包括<a>、<p>等),所以后续重新赋值时,原有的链接和结构全部丢失,只剩纯文本。

正确实现方式

方法1:用jQuery的unwrap()直接操作DOM(推荐)

直接找到目标区域内的所有<mark>标签,移除标签本身但保留内部内容,完全不影响其他HTML结构:

$(toolsProjects).each(function (index, tool) {
  const $targetElement = $('#' + tool['uid']);
  // 清除标题中的高亮标签
  $targetElement.find('.resource_title mark').contents().unwrap();
  // 清除描述中的高亮标签
  $targetElement.find('.text__container mark').contents().unwrap();
});
  • find('mark'):定位目标元素内所有<mark>标签
  • contents():获取<mark>标签包裹的所有内容(文本或嵌套HTML)
  • unwrap():移除<mark>标签,将内容直接留在原位置

方法2:通过HTML字符串替换(适合理解原理)

如果要使用字符串替换,不要用.text(),改用.html()获取完整HTML内容,再用正则全局替换目标标签:

$(toolsProjects).each(function (index, tool) {
  const $targetElement = $('#' + tool['uid']);
  // 处理标题
  let titleHtml = $targetElement.find('.resource_title').html();
  titleHtml = titleHtml.replace(/<\/?mark>/g, '');
  $targetElement.find('.resource_title').html(titleHtml);

  // 处理描述
  let descHtml = $targetElement.find('.text__container').html();
  descHtml = descHtml.replace(/<\/?mark>/g, '');
  $targetElement.find('.text__container').html(descHtml);
});
  • /<\/?mark>/g:正则表达式匹配<mark>和</mark>,g修饰符确保替换所有匹配项
  • .html():获取/设置包含完整HTML结构的内容,不会丢失其他标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 21:12:44