2012-11-08 33 views
0

我花了一些代碼從這裏: - How do I distinguish jQuery selector strings from other strings - 和修改它一下。但是,我無法讓比賽正常工作。我試過.test.exec字符串是html還是選擇器? JavaScript的

var htmlExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/; 
if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3 || htmlExpr.test(selector)) { 
    return true; 
} else { 
    return false; 
} 

我使用#mydiv<div class='gallery'>gallery</div>blahselector

兩個返回true。

發生了什麼事在這裏,我失蹤?

+0

**爲什麼**你在試這個?我不確定這將甚至可能與正則表達式,我看不到任何可能的用途。請注意,您使用的答案是關於測試字符串是否爲HTML,這與您在此處撰寫的內容相反。 –

+0

在你的'if'語句中,你爲什麼要使用這兩種方法?在你提供的SO問題中,答案是**使用正則表達式**或** charAt'&'length'方法。爲什麼還要在最後附加'htmlExpr.test(selector)'? – Ian

+0

@dystroy jQuery使用它來確定您作爲初始參數傳入的字符串是選擇器還是字符串。這有點複雜,我有一個簡單的用例,在一個小的內部庫更新中,這是必要的。 –

回答

1

#mydiv被返回true爲您專門在這部分|#([\w\-]+)$正則表達式檢查,你應該消除一部分,所以#mydiv不匹配,就像這樣:

var htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$/; 
if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3 || htmlExpr.test(selector)) { 
    return true; 
} else { 
    return false; 
} 

見工作demo

+0

它現在返回false兩個字符串=/ –

+0

/^(?:[^ <]*(<[\w\W]+>)[^>] * $ |([\ w \ - ] +)$)/似乎工作,至少對於這兩種情況!良好的捕獲(我在正則表達式是可怕的)。 –

+0

在我的答案中更新了正則表達式,請再次檢查它。 – Nelson

相關問題