提取数组中十六进制颜色时如何排除SVG fill属性匹配的色值
实现思路
你可以二选一任选方案实现:
- 方案1:使用负向回溯断言直接在正则层面过滤掉fill关联的色值,原有代码改动最小
- 方案2:先把字符串中所有fill相关的色值片段全部删除,再用原有逻辑提取,兼容性更强,适合需要适配低版本运行环境的场景
改造后代码(方案1)
const myArray = ["font-family: Roboto;\n\n @media ${sm} {\n background-color: #000;","height: 30px;\n object-fit: contain;\n margin-bottom: 6px;\n fill: #fff;", "<g\n className={fillableCn}\n transform=\"translate(-284.000000, -181.000000)\"\n fill=\"#298dcd\"\n >"] const findHex = () => { // 新增负向回溯断言,排除fill后带的色值,兼容带空格、引号的各种书写格式 let colorReg = /(?<!FILL\s*[:=]\s*["']?\s*)#[A-F0-9]{6}|#[A-F0-9]{3}/g; let colors = []; myArray.forEach((str) => { let strUpperCase = str.toUpperCase(); let match; // 重置正则匹配位置,避免上次匹配结果干扰 colorReg.lastIndex = 0; while ((match = colorReg.exec(strUpperCase)) !== null) { if (colors.includes(match[0])) { console.log("repeatedColors"); } else { colors.push(match[0]); } } }); console.log("-----------------"); console.log(colors); console.log("Number of colors: ", colors.length); console.log("-----------------"); }; findHex()
运行后输出的colors数组仅包含["#000"],符合排除fill关联色值的需求。
兼容低版本环境的方案2实现
如果你的运行环境不支持ES2018的负向回溯断言,可以在提取色值前先删除所有fill相关的色值片段,其余逻辑保持不变:
// 转大写后先替换掉所有fill关联的色值 strUpperCase = strUpperCase.replace(/FILL\s*[:=]\s*["']?\s*#[A-F0-9]{3,6}/g, '') // 再用原有正则提取即可 let colorReg = /#[A-F0-9]{6}|#[A-F0-9]{3}/g;
内容的提问来源于stack exchange,提问作者Mario Rodeghiero
相关产品推荐
相关产品推荐

