Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js if window.location.href not match, then jump to

How to make a window.location.href judge?

if window.location.href not match ?search=, make the current url jump to http://localhost/search?search=car

my code not work, or I should use indexOf to make a judge? Thanks.

if(!window.location.href.match('?search='){
    window.location.href = 'http://localhost/search?search=car';
}
like image 909
fish man Avatar asked Dec 09 '25 18:12

fish man


1 Answers

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='.

// 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';
} 
like image 126
Scott A Avatar answered Dec 13 '25 00:12

Scott A