首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用replace从html中删除<strong>标记

使用replace从html中删除<strong>标记
EN

Stack Overflow用户
提问于 2019-06-27 03:09:07
回答 2查看 277关注 0票数 0

我正在使用innerHTML methid从div中检索innerHTML。整个字符串中可以有多个<strong> </strong>实例

我正在做这样的事情来替换` `strong标签

inpStr=this.innerHTML 

inpStr=this.innerHTML.replace('<strong>','').replace('</strong>','')

但是,这只替换了强标记的第一个位置。我对正则表达式不是很熟悉,但我读到过使用/g替换所有出现的代码,但它也不起作用。

inpStr=this.innerHTML.replace('/<strong>/g','').replace('/<//strong>/g','')

更改到上面的代码根本不起作用,也不会替换任何东西,即使是第一个实例也不会。另外,我在/<//strong>/g',''中使用了两个//来转义strong中的结束标记,但我不确定。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-06-27 03:15:10

您需要转义/,否则JavaScript会认为您关闭了正则表达式。使用\可以做到这一点。所以/<\/strong>/g

document.getElementById("button").addEventListener("click", () => {
  const foo = document.getElementById("foo");
  foo.innerHTML = foo
    .innerHTML
    .replace(/<strong>/g, "")
    .replace(/<\/strong>/g, "");
});
<div id="foo">
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
  <strong>foo</strong>
</div>

<button id="button">Weaken</button>

票数 1
EN

Stack Overflow用户

发布于 2019-06-27 03:13:37

您可以使用以下函数

const replaceAll = (word, search, replacement) => {
    return word.replace(new RegExp(search, 'g'), replacement);
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56779587

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档