如何使用Jquery修改URL查询字符串

时间:2017-02-21 20:52:51

标签: javascript jquery url

我知道很多次都会问这个问题,但这些解决方案都不适合我。

我需要做的是将url查询字符串替换为其他值。

我需要从网址中替换?tab=。这是我的要求。

网址:

http://localhost:3000/private_search/search_all?tab=playlists&term=phy&utf8=✓&
rating[]=4&_=1487710144036

我需要做到:

http://localhost:3000/private_search/search_all?tab=featured&term=phy&utf8=✓&rating[]=4&_=1487710144036

http://localhost:3000/private_search/search_all?tab=all_schools&term=phy&
utf8=✓&rating[]=4&_=1487710144036

decodeURIComponent(this.url)返回:

http://localhost:3000/private_search/search_all?tab=playlists&term=phy&utf8=✓&
rating[]=4&_=1487710144036


$("#featured-url").attr('href', decodeURIComponent(this.url)); // need to change url here 
 $("#school-url").attr('href', decodeURIComponent(this.url));  // need to change url here 

1 个答案:

答案 0 :(得分:2)

正则表达非常强大,非常适合这种情况,但很难学习。这是在你的例子中使用它。

$("#featured-url").attr('href',
  $("#featured-url").attr('href').replace(/\?tab=[^&]+/, '?tab=featured')
);

$("#school-url").attr('href',
  $("#school-url").attr('href').replace(/\?tab=[^&]+/, '?tab=all_schools')
);

以下是对RegEx的解释:

  • \?匹配?字符(逃脱,因为?有其他含义)
  • tab=匹配该字符串
  • [^&]匹配除&
  • 之外的任何内容
  • +预计会有一个或多个上一场比赛
相关问题