可以使用以下正则表达式提取样式代码:

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

解释:

  • <style> 匹配 <style> 标签开头
  • ([\s\S]*?) 匹配任意字符,非贪婪模式,直到下一个 </style> 出现
  • <\/style> 匹配 </style> 标签结尾

示例代码:

const html = '<style>\n  div {\n    background-color: red;\n    width: 600px;\n    height: 100px;\n    color: blue;\n    text-decoration: underline;\n  }\n</style>\n<div>这是一段文字</div>';

const styleRegex = /<style>([\s\S]*?)<\/style>/;

const styleMatch = html.match(styleRegex);

if (styleMatch) {
  const styleCode = styleMatch[1];
  console.log(styleCode);
} else {
  console.log('样式代码未找到');
}

输出结果:

div {
  background-color: red;
  width: 600px;
  height: 100px;
  color: blue;
  text-decoration: underline;
}
style div background-color red; width 600px; height 100px; color blue; text-decoration underline; stylediv这是一段文字div用正则提取样式代码

原文地址: https://www.cveoy.top/t/topic/1DY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录