2 回答
TA贡献1848条经验 获得超10个赞
试试这个选项,它匹配所有的 HTML 标签,不包括那些有属性的标签class="keep-this"。
let str = 'You have to pay <input class="some-class"/> blah <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';
console.log(str.replace(/<\s*([^\s>]+)(?:(?!\bclass="keep-this")[^>])*>(.*?)(?:<\/\1>)|<\s*([^\s>]+)(?:(?!\bclass="keep-this")[^>])*\/>/g, "$2"));
以下是正则表达式模式的解释:
< match < of an opening tag
\s* optional whitespace
([^\s>]+) match and capture the HTML tag name in $1 (\1)
(?:(?!\bclass="keep-this")[^>])* match remainder of tag,
so long as class="keep-this" is not seen
> match > of an opening tag
(.*?) match and capture the tag's content in $2,
until hitting the nearest
(?:<\/\1>) closing tag, which matches the opening one
| OR
<\s*([^\s>]+) match a standalone tag e.g. <input/>
(?:(?!\bclass="keep-this")[^>])* without a closing tag
\/> which matches
然后,我们只需将所有此类匹配项替换为空字符串,即可有效地删除它们。
TA贡献1911条经验 获得超7个赞
如果你想删除所有没有类的 html 元素,keep-this你也可以使用DOMParser,例如使用:not。
let str = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';
let parser = new DOMParser();
let doc = parser.parseFromString(str, "text/html");
doc.querySelectorAll("body *:not(.keep-this)").forEach(e => e.replaceWith(e.innerHTML));
console.log(doc.body.innerHTML);
添加回答
举报