2016-10-05 81 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]')); 

}());