简体   繁体   English

JS:如何使用正则表达式从 HTML 字符串中删除样式标签及其内容?

[英]JS: How to remove style tags and their content from an HTML string, using regular expressions?

I need to remove the entire content of style tags from an html string, in multiple occurrences.我需要从 html 字符串中多次删除样式标签的全部内容。 I can't use a DOM parser for it.我不能使用 DOM 解析器。

How could i do this, in JavaScript?我怎么能在 JavaScript 中做到这一点?

 var string = "<style>someHTMLStuff</style> non style <html>stuff</html>" var s = string.replace(/<style.*?<\\/style>/g, '') console.log(s);

I am assuming you wanted the entire style tag removed, not just its contents我假设您希望删除整个样式标签,而不仅仅是其内容

Edit: quotes编辑:引号

For those that land here in 2020 this worked for me.对于那些在 2020 年登陆这里的人来说,这对我有用。

string.replace(/(<style[\w\W]+style>)/g, "")

As Bergi alluded to in the OP comments thought, this should be regarded as a last resort if there are no better options.正如 Bergi 在 OP 评论中提到的那样,如果没有更好的选择,这应该被视为最后的手段。 RegEx is not the best way to deal with HTML. RegEx 不是处理 HTML 的最佳方式。

<style([\\S\\s]*?)>([\\S\\s]*?)<\\/style>

https://regex101.com/r/C28OPE/1 https://regex101.com/r/C28OPE/1

This worked for me even with multiple tags.即使有多个标签,这对我也有用。 credit信用

To replace all style attributes in a HTML element (innerHTML) :替换 HTML 元素 (innerHTML) 中的所有样式属性:

<div id="el">
  <p style="font-weight:bold">Line 1</p>
  <p style="color:red">Line 2</p>
</div>

//script
let element = document.getElementById('el')
element.innerHTML.replace(/style=\".*"/gm,'')

This will remove all elements style attribute in element by id el.这将通过 id el 删除元素中的所有元素样式属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM