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

发布于 2024-12-14 04:24:50 字数 366 浏览 0 评论 0原文

如何进行window.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';
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千鲤 2024-12-21 04:24:50

有几件事:你缺少一个右括号,并且你需要转义 ?因为它对于正则表达式很重要。使用 /\?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';
} 

或者

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

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';
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文