能否将CSS style标签转换为JavaScript对象?附方案探讨
从HTML内联样式提取CSS类并转换为指定JS对象
问题描述
我有一段包含内联样式的HTML代码,其中style标签里的CSS类存在语法错误(border属性的引号位置不对),现在我想把这些CSS类提取出来,转换成键为类名(带
.)、值为完整样式字符串的JavaScript对象。我的HTML代码:
<head> <style> .class1 { background-color: white; border: "1px dashed black; } .class2 { background-color: dodgerblue; border: "1px dashed orange; } </style> </head>期望得到的JS对象:
{ ".class1": "background-color: white; border: 1px dashed black;", ".class2": "background-color: dodgerblue; border: 1px dashed orange;" }
我的解决方案
Hey there! Let's work through this step by step. First, we need to fix the wonky quotes in the original CSS, then parse the classes and their styles into the object you want. Here's how to do it:
1. 完整实现代码
// Grab the raw CSS text from the style tag const rawCss = document.querySelector('style').textContent; // Fix the broken quotes in border properties first const cleanedCss = rawCss.replace(/border: "/g, 'border: '); // Regex to match each class selector and its style block const classPattern = /\.([\w-]+)\s*{([^}]+)}/g; const styleObject = {}; let matchResult; // Loop through all matches to build our object while ((matchResult = classPattern.exec(cleanedCss)) !== null) { const fullClassName = `.${matchResult[1]}`; // Clean up the style string: trim whitespace, fix spacing const cleanedStyles = matchResult[2] .trim() .replace(/\s+/g, ' ') .replace(/;\s*/g, '; ') .trim(); styleObject[fullClassName] = cleanedStyles; } console.log(styleObject);
2. 代码解释
- 修复CSS语法:原代码里
border属性的开头引号是错误的,我们用replace()把这些多余的引号去掉,让CSS可以正常被解析。 - 正则匹配类与样式:正则表达式
\.([\w-]+)\s*{([^}]+)}会匹配所有以.开头的类选择器,同时捕获类名和花括号内的所有样式内容。 - 整理样式字符串:通过
trim()去除首尾空格,replace(/\s+/g, ' ')把多个连续空格合并成一个,replace(/;\s*/g, '; ')确保每个样式声明后都有一个空格,让最终的样式字符串和你期望的格式一致。
运行这段代码后,就能得到你想要的JavaScript对象啦!
内容的提问来源于stack exchange,提问作者Ricardo Carvalho
相关产品推荐
相关产品推荐

