天天看点

【前端】使用JS替换URL的参数(代码案例)

现有一个URL:

<!-- lang: js -->
http://www.jynet.top?query=name&query_value=abc
           

想要替换其中的参数:query,用JS该怎么做呢?

不纠结......代码如下:

<!-- lang: js -->
var key = 'title';
var value = 'defg';
var currentURL = http://www.jynet.top/blog?query=name&query_value=abc;
var targetURL = '';
if ((currentURL.charAt(currentURL.length - 1) == "&") == false) {
  currentURL += '&';
}
var targetURL_tmp = currentURL.replace(/(query=).*?(&)/, '$1' + key + '$2');
targetURL = targetURL_tmp.replace(/(query=).*?(&)/, '$1' + value + '$2');
           

继续阅读