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';
}