Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js如果window.location.href不匹配,则跳转到_Javascript_Window.location - Fatal编程技术网

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

Javascript js如果window.location.href不匹配,则跳转到,javascript,window.location,Javascript,Window.location,如何制作窗口.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'; } 有两件事:你错

如何制作
窗口.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';
}

有两件事:你错过了一个即将结束的帕伦,你需要逃离这个世界吗?因为它对正则表达式很重要。使用
/\?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';
} 


是的,疏忽的
遗漏了一个结束参数
,主要结果是
转义?
谢谢。@Scott a:你提到:在你的答案中使用/\?search=/或'\?search='但是在你的第一个例子中,你使用了'\\?search='为什么不使用'\?search='?@塔里克在第一个例子中,正则表达式本身需要反斜杠,但要在字符串中表示反斜杠,还需要转义反斜杠。。。用另一个反斜杠。因此\\在发送到match()函数时变为\。在第二个示例中,/../construct直接创建一个正则表达式,因为它不首先遍历字符串,所以不需要转义它。
// 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';
}