[英]Using replace to remove <strong> tags from html
I am using innerHTML
methid to retrieve the innerHTML from a div
. 我正在使用
innerHTML
方法从div
检索innerHTML。 There can be multiple instances of <strong>
</strong>
throughout the string 整个字符串中可能存在
<strong>
</strong>
多个实例
I am doing something like this to replace the `strong tag 我正在做这样的事情来代替`strong标签
inpStr=this.innerHTML
inpStr=this.innerHTML.replace('<strong>','').replace('</strong>','')
However, this only replaces the first occerance of strong tag. 但是,这仅取代了第一次出现强标签。 I am not very familiar with regex but I read about using
/g
to replace all occurrence but it does not work either. 我对regex不太熟悉,但是我读到有关使用
/g
替换所有出现的内容,但它也不起作用。
inpStr=this.innerHTML.replace('/<strong>/g','').replace('/<//strong>/g','')
Changing to above code does not work at all and does not replace anything at all, not even the first instance. 更改为上述代码根本不起作用,甚至根本无法替换任何东西。 Also I am using the double // in
/<//strong>/g',''
to escape the closing tag in strong but I am not sure. 我也在
/<//strong>/g',''
使用double // /<//strong>/g',''
来以强势转义结束标签,但我不确定。
\\/
not //
\\/
不//
\\/?
\\/?
inpStr=this.innerHTML.replace('/<\/?strong>/g','')
You can use the following function 您可以使用以下功能
const replaceAll = (word, search, replacement) => {
return word.replace(new RegExp(search, 'g'), replacement);
};
You need to escape the /
otherwise JavaScript thinks you closed your Regular Expression. 您需要转义
/
否则JavaScript会认为您关闭了正则表达式。 Do that with a \\
. 用
\\
做到这一点。 So /<\\/strong>/g
. 所以
/<\\/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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.