【问题标题】:Extract all css selectors with javascript [closed]使用 javascript 提取所有 css 选择器 [关闭]
【发布时间】:2019-03-24 17:50:18
【问题描述】:

我需要为选择器解析 CSS 文件并使用 Javascript 正确查找文件中的所有 CSS/CSS3 选择器。

例如:

.hello { ... declaration ... }
.world::after { ... declaration ... }
#id1, #id2 { ...declaration... }.top{ ..declaration.. }

我需要得到一个元素数组:[".hello", ".world::after", "#id1", "#id2", ".top"]

谢谢!

【问题讨论】:

  • 你不能只要求堆栈溢出的人来解决你的问题,而不做任何实际的工作来找到解决方案。向我们展示您尝试过的代码。向我们展示您所做的研究。见this。

标签: javascript css regex css-selectors


【解决方案1】:

您可以使用以下正则表达式来拆分您的文本,因此您有一个匹配数组:

/\{.*?\}|,|\>|\s/g

正则表达式会找到我们不想要的:首先是“{”,然后是零个或多个任意字符(非贪婪)或逗号或“>”或空格。它使用 Global 标志来捕获所有内容。

然后你需要用一个空字符串替换那些匹配并且你有一个选择器数组。

Example:

var css = '.hello { ... declaration ... }\r\n'
    + '.world::after { ... declaration ... }'\r\n'
    + '#id1, #id2 { ...declaration... }.top{ ..declaration.. }';

var selectorArray = css.split(/\{.*?\}|,|\>|\s/g);

您必须删除数组中的空元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2017-11-16
    • 2013-11-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多