我正在使用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中的结束标记,但我不确定。
发布于 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>
发布于 2019-06-27 03:13:37
您可以使用以下函数
const replaceAll = (word, search, replacement) => {
return word.replace(new RegExp(search, 'g'), replacement);
};
https://stackoverflow.com/questions/56779587
复制相似问题