3

如何做window.location.href法官?

如果window.location.href不匹配?search=,则使当前url跳转到http://localhost/search?search=car

我的代码不起作用,还是我应该indexOf用来做判断?谢谢。

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

1 回答 1

8

有几件事:你缺少一个结束括号,你需要逃避 ? 因为它对正则表达式很重要。使用/\?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';
} 
于 2011-11-07T19:17:10.410 回答