js如果window.location.href不匹配,则跳转到

时间:2011-11-07 19:10:59

标签: javascript window.location

如何判断window.location.href

如果window.location.href?search=不匹配,请将当前网址跳至http://localhost/search?search=car

我的代码不起作用,或者我应该使用indexOf来判断?感谢。

if(!window.location.href.match('?search='){
    window.location.href = 'http://localhost/search?search=car';
}

1 个答案:

答案 0 :(得分:6)

有几件事:你错过了一个关闭的人,你需要逃避?因为它对正则表达式很重要。使用/ \?search = /或'\?search ='。

// Create a regular expression with a string, so the backslash needs to be
// escaped as well.
if (!window.location.href.match('\\?search=')) {
    window.location.href = 'http://localhost/search?search=car';
} 

// Create a regular expression with the /.../ construct, so the backslash
// does not need to be escaped.
if (!window.location.href.match(/\?search=/)) {
    window.location.href = 'http://localhost/search?search=car';
}