现有一个URL:
<!-- lang: js -->
http://abcccc.com/blog?query_key=name&query_value=abc
想要替换其中的参数:query_key,用JS该怎么做呢?
这里记录一种方案:
<!-- lang: js -->
var key = 'title';
var value = 'defg';
var currentURL = http://abcccc.com/blog?query_key=name&query_value=abc;
var targetURL = '';
if ((currentURL.charAt(currentURL.length - 1) == "&") == false) {
currentURL += '&';
}
var targetURL_tmp = currentURL.replace(/(query_key=).*?(&)/, '$1' + key + '$2');
targetURL = targetURL_tmp.replace(/(query_value=).*?(&)/, '$1' + value + '$2');
解释: replace中使用分组, '$1' 代表 'query_key=', '$2'代表 '&',替换的就是这两者之间的部分; 但是url中最后一个参数往往不会含有'&',所以在url结尾添加一个'&'。