2017-03-06 64 views
2

使用我有以下代碼,這是我從另一個SO問題偷走,試圖逃跑字符串作爲jQuery選擇

$('#'+'^`test'.replace(/[!"#$%&'()*+,.\/:;<=>[email protected][\\\]^`{|}~]/g, "\\\\$&")) 

產生下面的錯誤。

Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)

我只是有一些標識瘋狂的字符,如^和`,我需要jQuery的不嗆。我不知道爲什麼這個錯誤發生的事情,因爲如果我手動添加斜線到字符串一樣,

$('#'+'\\^\\`test') 

然後正常工作。正則表達式有什麼問題?

回答

3

I just have some IDs with crazy characters, like^and `, that I need jQuery to not choke on.

到目前爲止,以解決最簡單的方法就是使用屬性選擇:

$('[id="' + theId + '"]').doSomething(); 

只要theId不包含反斜線或雙引號,不需再逃避。

+0

有趣的是,我不知道該如何工作。我想我會使用getElementById,但我想這是對我的問題最直接的答案。 – Moss

+0

@Moss:這是[屬性值選擇器](https://www.w3.org/TR/css3-selectors/#attribute-representation)。但是,是的,getElementById是一個很好的方法(爲什麼我沒有提到它?!),當ID可以是「狂野」時。 '$(document.getElementById(theId))。doSomething();' –

+0

什麼意思是我不明白你的解決方案如何工作,但我的第一次嘗試沒有。特定於jQuery的東西? – Moss

0

你需要2次逃生。首先替換/正則表達式需要逃脫才能寫出逃脫。 $()需要從jquery中獲得下一個轉義。

更清晰的語法爲postet正則表達式是:

"#^bla`".replace('^','\\\^').replace('`','\\\`'); 

將取代 「#^ bla`」 到 「#^ \\ \\ BLA'」。

Uncaught Error: Syntax error, unrecognized expression: #\\^\\`test(…)

如果你想使用您正則表達式還必須轉義[]與\ [和\]。

"+".replace(/[!"#$%&'()*+,.'()*+,.\/:;<=>[email protected]\[\\\]^`{|}~]/g, "yes") 
2

另一個解決辦法是使用香草getElementById,不解析選擇。這樣你仍然有選擇ID的效率:

let res = $(document.getElementById('^`test')); 
+0

Doh!當然。 –

+0

對潛伏者的警告:'let'是ES2015 +,它在野外的某些瀏覽器中不起作用。 –

0

如何使用它?

const $ID = function(selector){ 
    return $('[id="' + selector.match(/#?(\S+)/)[1] + '"]') 
} 

然後你可以使用它,就像jQuery的

$ID('#^`div')