admin管理员组

文章数量:1278975

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

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';
}
Share Improve this question asked Nov 7, 2011 at 19:10 fish manfish man 2,72021 gold badges55 silver badges94 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 8

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

本文标签: javascriptjs if windowlocationhref not matchthen jump toStack Overflow