2016-10-05 64 views
0

我想看看我現在的網址,例如:檢查URL包含文本和括號

http://www.dummy.com/subpageone/pagetwo.html?ineedthis[andthis]&butnotthis 

我想要一個alert如果我得到確切ineedthis[andthis]

到目前爲止我

if (window.location.href.indexOf("ineedthis") > -1) { 
    alert("your url contains it"); 
} 

但是這還不夠。我如何檢查[andthis]?我嘗試了一些變化,但沒有運氣。

indexOf("ineedthis\[andthis\]") 
indexOf("ineedthis%5andthis%5D") 
if (/ineedthis\[andthis\]/.test(window.location.href)) 

感謝您的任何建議。

+0

'的indexOf( 「ineedthis [andthis]」)'對我來說工作正常 - 回報指數45,在你給的例子URL。另外,不需要轉義方括號。 – Utkanos

+0

可能是你用'window.location.href'獲得編碼url。在比較之前先嚐試解碼它。 – vijayP

回答

2

只需使用:

if(window.location.href.indexOf("ineedthis[andthis]") > -1) { 
    alert("your url contains it"); 
} 

至於searchValue爲的indexOf是字符串,而不是正則表達式。

+0

我就像磚頭一樣啞......是的,那樣做了。多謝你們。 :) – TZP

0

也可以使用正則表達式做同樣的:

(function(){ 

var pattern = new RegExp(/ineedthis\[andthis\]/); 
alert(pattern.test('ineedthis[andthis]')); 

}());