2011-05-15 54 views
2

我想检查字符串的“类型”。特别是,如何区分jQuery选择器字符串与其他字符串?换句话说,如何在下面的代码中实现selectorTest?如何区分jQuery选择器字符串与其他字符串

var stringType = function(value) { 
     var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/; 

     if (htmlExpr.test(value)) { 
      return "htmlstring"; 
     } 
     if (selectorTest) { 
      return "selectorstring"; 
     } 
     return "string"; 
    } 
+0

你不能。 jQuery选择器几乎可以做任何事情。 – JohnP 2011-05-15 10:28:29

回答

5

您可以do what jQuery does内部和检查它是否是HTML或不the following regex

/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/ 

如:

var stringType = function(value) { 
    var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/; 

    if (htmlExpr.test(value)) { 
     return "htmlstring"; 
    } 
    if (selectorTest) { 
     return "selectorstring"; 
    } 
    return "string"; 
} 

注意,在较新版本的jQuery,there's another check明确地针对“以<开始”和“以结束”“跳过正则表达式(纯粹为了速度)。 The check looks like this核心(如jQuery的1.6.1):

if (typeof selector === "string") { 
    // Are we dealing with HTML string or an ID? 
    if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { 
     // Assume that strings that start and end with <> are HTML and skip the regex check 
     match = [ null, selector, null ]; 
    } else { 
     match = quickExpr.exec(selector); 
    } 
+0

你并没有完全回答我的问题,但我决定按照你的建议去做。也就是说,我只是说一个字符串是一个选择器字符串,如果它不是一个html字符串。 谢谢! – mcthuesen 2011-05-16 23:33:01

+0

不幸的是,错了。您提供的正则表达式仅匹配仅包含ID的HTML和选择器。当第二组('|#(\ w \ - ] +)$)')匹配时,[字符串被认为是仅用于ID的选择器](https://github.com/jquery/jquery/blob/主/ SRC/core.js#L110)。我不确定,也许它是为性能而完成的,但是测试字符串是否为HTML的真正正则表达式将是'/^\ s * [^>] * \ s * $ /'。 – Septagram 2013-08-22 10:55:09

-2

也许($(value).size()>0)?

它会测试选择器是否被识别。

但在我看来,这是有点奇怪的做法...

+0

它可能仍然是一个有效的选择器,但只是不匹配任何元素... – 2011-05-15 10:36:17

+0

如果您的字符串包含无效字符(将抛出异常),则绝对为false。 – 2012-10-29 22:16:48

相关问题