javascript js 如果 window.location.href 不匹配,则跳转到
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8041311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
js if window.location.href not match, then jump to
提问by fish man
How to make a window.location.href
judge?
怎么做window.location.href
裁判?
if window.location.href
not match ?search=
, make the current url jump to http://localhost/search?search=car
如果window.location.href
不匹配?search=
,则使当前url跳转到http://localhost/search?search=car
my code not work, or I should use indexOf
to make a judge? Thanks.
我的代码不起作用,还是我应该用来indexOf
判断?谢谢。
if(!window.location.href.match('?search='){
window.location.href = 'http://localhost/search?search=car';
}
回答by Scott A
A couple of things: you're missing a closing paren, and you need to escape the ? because it's significant to regular expressions. Use either /\?search=/ or '\?search='.
有几件事:你缺少一个结束括号,你需要逃避 ? 因为它对正则表达式很重要。使用 /\?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';
}
or
或者
// 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';
}