2011-10-05 144 views
2

我粘貼確切的字符串JavaScript顯示:爲什麼在這種情況下string.search失敗?

string: "testare atasament fisier,tip nota - reamintire (1),Diverse,Telefon,Fisier,tip nota Azom" without the "" 

substring: "tip nota - reamintire (1)" again without the "" 

只是寫那些「」表明,沒有空的空間的任何地方有趣(也在代碼進行覈對)

結果
string.search(substring); 

總是-1,怎麼回事?哪個角色搞亂了搜索?

注意,我不使用的變量名字符串,字符串在我的實際代碼

回答

2

它爲我工作 - 使用indexOf

"testare atasament fisier,tip nota - reamintire (1),Diverse,Telefon,Fisier,tip nota Azom" 
.indexOf("tip nota - reamintire (1)"); 

產量

25 

搜索需要正則表達式,其中indexOf tak es一個字符串。

「tip nota - reamintire(1)」中的括號充當一個組,您必須將它們轉義以匹配實際的括號。

+0

很好,我想這是在當天爲時已晚,我想簡單的解決方案。謝謝。 – Bogdan

3

search方法接受一個正則表達式對象,如果給它一個字符串,它將用於創建一個正則表達式對象。

參考:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/search

()在正則表達式的特殊含義,所以他們不包括在應匹配的字符。你實際上正在尋找字符串"tip nota - reamintire 1"

您可以使用\字符來轉義正則表達式中的字符。如果你在一個字符串使用它們,你必須逃離\字符,所以:

var substring = "tip nota - reamintire \\(1\\)"; 

您還可以使用正則表達式文本:

var substring = /tip nota - reamintire \(1\)/; 
2

這是因爲search function有一個正則表達式作爲參數。 你有\\對括號進行轉義:

var string= "testare atasament fisier,tip nota - reamintire (1),Diverse,Telefon,Fisier,tip nota Azom" ; 
var substring = "tip nota - reamintire (1)" ; 
var substring2 = "tip nota - reamintire \\(1\\)" ; 

alert(string.search(substring)); // -1 
alert(string.search(substring2)); // 25 
相關問題