1

我编写了非常基本的正则表达式来验证 querySelectorAll() 方法的参数。验证了一些随机值,似乎它工作正常。

我只是想知道是否可以进行一些改进。

正则表达式可能会遗漏一些验证,但我的主要问题是关于我的方法,关于我编写这个正则表达式的方式。我对正则表达式也很陌生。如果我在表现方面犯了任何重大错误,请指出我。

var p = /^([A-Za-z0-6]*|\*)?((?:(?:#|\.|:|\[)[-A-za-z0-9()+\s"=|^$*]+)*)$/;

/* 


[A-Za-z0-6]* Type selector
\* Universal selector
#|\.|:|\[ for id,class,attribute and psuedo classes
[-A-za-z0-9()+\s"=|^$*]+ id,class, attribute or pseudo class value


*/

var stringArray = [
"div",
"div:first-child",
"div#id",
"div123",
"h1",
"*.warning",
".warning",
"*#myid",
"#myid",
"p.pastoral.marine",
"h1#chapter1",
"*#z98y",
"a.external:visited",
"a:visited",
"a:focus:hover",
"tr:nth-child(2n+1)",
"tr:nth-child(odd)",
"p:nth-child(4n+4)",
"foo:nth-child(0n+5)",
"foo:nth-child(5)",
":nth-child( 3n + 1 )",
"img:nth-of-type(2n+1)",
"h2:nth-of-type(n+2):nth-last-of-type(n+2)",
"h2:not(:first-of-type):not(:last-of-type)",
"h1[title]",
'span[class="example"]',
'span[hello="Cleveland"][goodbye="Columbus"]',
'a[hreflang|="en"]',
'object[type^="image"]',
'a[href$=".html"]',
'p[title*="hello"]'
];
4

1 回答 1

0

验证选择器的最简洁可靠的方法querySelectorAll是调用函数本身并检查它是否抛出:

const validateSelector = selector => {
  try { document.querySelectorAll(selector) }
  catch { return false }
  return true;
}

console.log(validateSelector('abc!?#&^123')); // false
console.log(validateSelector('div > text')); // true

于 2020-07-26T00:55:41.447 回答