You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

拆分字符串生成JavaScript对象时如何保留key中的/*! */字符

问题解决说明

根因分析

你当前实现的正则/\/\*\!\s*(.*?)\s*\*\//仅将注释中间的文本作为捕获组,调用split方法时只会把捕获组内的内容放入结果数组,因此外层的/*!和*/标记没有被纳入key中,导致丢失。

修正方案

方案1:修改原有split逻辑

仅调整正则,将完整的注释块整体作为捕获组即可,其他逻辑保持不变:

const a = "/*! ###################################################### # Test.cs #  RELEASE: 1.1.1 # BUILD DATE: Fri Oct 30 2020 15:25:57 GMT-0700 (PDT) # COPYRIGHT ###################################################### *//*! MISC + SASS */a:focus,button:focus,div[tabindex]:focus,li[tabindex]:focus,span[tabindex]:focus{outline-offset:2px;outline-width:2px!important;outline-style:dotted!important;outline-color:currentColor}/*! GENERIC - BGIMG */.bgimg{background-size:cover;background-position:50% 50%;background-repeat:no-repeat}/*! CG2111 - test */span{color:red}/*! CG2112 - test */span{color:red}/*! INFO */#id{content:'1.1.1'}";

const result = {},
  // 正则修改为捕获完整的/*! ... */注释块
  temp = a.split(/(\/\*!\s*.*?\s*\*\/)/).slice(1);
while (temp.length) result[temp.shift()] = temp.shift();

console.log(result);

方案2:使用matchAll实现(逻辑更直观)

直接匹配每一组注释和对应的后续样式内容,无需处理split生成的多余空项:

const a = "/*! ###################################################### # Test.cs #  RELEASE: 1.1.1 # BUILD DATE: Fri Oct 30 2020 15:25:57 GMT-0700 (PDT) # COPYRIGHT ###################################################### *//*! MISC + SASS */a:focus,button:focus,div[tabindex]:focus,li[tabindex]:focus,span[tabindex]:focus{outline-offset:2px;outline-width:2px!important;outline-style:dotted!important;outline-color:currentColor}/*! GENERIC - BGIMG */.bgimg{background-size:cover;background-position:50% 50%;background-repeat:no-repeat}/*! CG2111 - test */span{color:red}/*! CG2112 - test */span{color:red}/*! INFO */#id{content:'1.1.1'}";

const result = Object.fromEntries(
  [...a.matchAll(/(\/\*!\s*.*?\s*\*\/)(.*?)(?=\/\*!|$)/g)]
    .map(item => [item[1], item[2]])
)

console.log(result);

两种方案输出的结果都和你期望的结构完全一致。

内容的提问来源于stack exchange,提问作者user5711656

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 19:15:04