如何解析和提取CSS选择器作为字符串? [英] How to parse and extract CSS selectors as strings?

查看:511
本文介绍了如何解析和提取CSS选择器作为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将css选择器提取为字符串最简单的方法是什么?

What is the simplest way to extract css selectors as strings?

将此作为输入:

#article{width:690px;overflow:hidden}
#article h2:first-child a{text-decoration:none}
#works .project p:last-child{margin-top:20px;font-size:13px}
#works .project img, #works .info img{width:680px;min-height:400px;border:1px dotted #ccc;margin-bottom:40px}

如何获取如下选择器列表:

How can I get a list of selectors such as this:

var selectors = ['#article','#article h2:first-child a','#works .project p:last-child','#works .project img']


推荐答案

我最终得到的解决方案是:

Here is the solution I ended up with:


  1. 用一些独特的字符替换大括号及其内容。正则表达式从这里被挑选使用JavaScript匹配CSS选择器RegExp

  2. 分隔这些唯一字符的列表。

这里为documention:

Just wanted to post it here for documention:

var css = "#article[type=x]{width:690px;overflow:hidden}#article h2:first-child a{text-decoration:none}#works .project p:last-child{margin-top:20px;font-size:13px}#works .project img, #works .info img{width:680px;min-height:400px;border:1px dotted #ccc;margin-bottom:40px}"
var found = css.replace(/{([^}]*)}/gm,"~~~").split("~~~");

document.write(found);

这篇关于如何解析和提取CSS选择器作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆