如何将HTML中style属性的属性名统一转换为全小写
内联style属性名小写校验与格式化方案
你可以通过以下JS函数实现自动识别HTML中的内联style属性,将属性名统一转为小写,同时支持结合你提供的样式映射表做合法性校验:
1. 基础版(仅做大小写转换)
核心逻辑是提取style属性内容,拆分每个键值对后将属性名转为小写,再重新拼接:
// 传入原始HTML字符串,返回处理后的HTML function formatStyleAttrToLower(htmlStr) { // 匹配所有style属性(支持单/双引号) return htmlStr.replace(/style\s*=\s*["']([^"']*)["']/gi, (match, styleContent) => { // 拆分每个样式键值对,过滤空项 const styleItems = styleContent.split(';').filter(item => item.trim()); const processedItems = styleItems.map(item => { const [prop, value] = item.split(':').map(part => part.trim()); // 属性名转小写,值保留原样 return `${prop.toLowerCase()}: ${value}`; }); return `style="${processedItems.join('; ')}"`; }) } // 测试用例 const rawHtml = `<div style='MARGIN:10px; FLOAT:left'></div>`; console.log(formatStyleAttrToLower(rawHtml)); // 输出:<div style="margin: 10px; float: left"></div>
2. 增强版(结合样式映射表校验)
如果需要校验属性是否为你允许的样式,可结合你提供的styles映射表做过滤/告警:
// 你的样式映射表 const styles = { 'font': 'font', 'fontSize': 'font-size', 'fontFamily': 'font-family', 'fontVariant': 'font-variant', 'fontWeight': 'font-weight', 'fontStyle': 'font-style', 'margin': 'margin', }; // 提取允许的CSS属性名集合 const allowedCssProps = new Set(Object.values(styles)); function formatAndValidateStyle(htmlStr, enableAlert = false) { return htmlStr.replace(/style\s*=\s*["']([^"']*)["']/gi, (match, styleContent) => { const styleItems = styleContent.split(';').filter(item => item.trim()); const validItems = []; styleItems.forEach(item => { const [prop, value] = item.split(':').map(part => part.trim()); const lowerProp = prop.toLowerCase(); if (allowedCssProps.has(lowerProp)) { validItems.push(`${lowerProp}: ${value}`); } else if (enableAlert) { console.warn(`非法样式属性:${prop},已被过滤`); } }); return `style="${validItems.join('; ')}"`; }) } // 测试用例 const rawHtml = `<div style='MARGIN:10px; FLOAT:left'></div>`; console.log(formatAndValidateStyle(rawHtml, true)); // 输出:<div style="margin: 10px"></div>,同时控制台告警FLOAT是非法属性
场景适配
- 编辑器插件场景:可以在粘贴事件触发时调用上述函数处理粘贴的HTML内容,再插入到编辑器中
- 批量处理文件场景:可以用NodeJS批量读取本地HTML文件内容,调用函数处理后回写文件
内容的提问来源于stack exchange,提问作者user13424765
相关产品推荐
相关产品推荐

