2011-05-15 52 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

相關問題