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

fis*_*man 2 javascript window.location

如何做出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';
}
Run Code Online (Sandbox Code Playgroud)

Sco*_*t A 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';
} 
Run Code Online (Sandbox Code Playgroud)

要么

// 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';
} 
Run Code Online (Sandbox Code Playgroud)