基本上我试图提取一些不同的 css 选择器的最后一个标签名称。
我已经在 javascript 中成功地实现了我正在谈论的内容,我正在寻找一种更紧凑的方式,最好只使用一个正则表达式。
这是我成功完成的工作。
//Trim selector, remove [attr] selectors due to conflicts, and standardize >,~,
selector=selector.replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g,'')
selector=selector.replace(/\[[^\]]*\]/g,'[]').replace(/\s*([>~\s])\s*/g,'$1');
var theSplit = selector.split(/[>~\s]/);
selector = /^[^.\[:]*/.exec(theSplit[theSplit.length-1]) || "*";
我只希望支持 Internet Explorer 7 100% 支持的 css 2.0 选择器。
例如 + 选择器和 :first-child 选择器在 ie7 中是静态的,因此我不需要支持它们。 这是必须工作的 css 选择器列表。
#test span ul a
#test >span[style="background:green"]
#id + span ~ article.class
section header.class
body
div
body div
div p
div > p
div ~ p
div[class^=exa][class$=mple]
div p a
.note
div.example
ul .tocline2
#title
h1#title
div #title
ul.toc li.tocline2
ul.toc > li.tocline2
a[href][lang][class]
div[class]
div[class=example]
div[class^=exa]
div[class$=mple]
div[class*=e]
div[class|=dialog]
div[class!=made_up]
div[class~=example]
编辑:我最终使用了这个脚本。它甚至考虑到了通用选择器
var lastTagName = selector.replace(/\[[^\]]+\]|[\.#][\w-]+|\s*$/g,'').replace(/^.*[^\w]/, '')||'*'
最佳答案
作为最后一步,选择器开头的内容应该很容易删除,所以让我们先关注从末尾删除这两种类型的垃圾。那是方括号中的内容和 .
或 #
.
str = str.replace(/\[[^\]]+\]/g, '').replace(/[\.#][a-z0-9]+/gi, '');
也就是说,删除方括号之间的所有内容(在整个表达式中;如果它更早地捕捉到东西就没关系),然后同样适用于 .
和 #
选择器。
然后,最后,删除导致非字母数字字符的所有内容,包括空格、>
等等。这将只留下字符串中的最后一个“单词”(在本例中为标签名称):
str = str.replace(/^.*[^a-z0-9]/i, '');
一个 jsFiddle 来试试:http://jsfiddle.net/JAA98/
关于javascript - 提取各种选择器的最后一个 tagName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4004358/