如何判断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';
}
答案 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';
}