如何在javascript中正确添加搜索查询参数到包含哈希的url?

时间:2016-09-24 15:41:04

标签: javascript

我想为每个链接添加基本网址和查询参数:

function buildURL(relativePath) {
    var url = new URL('http://example.com/' + relativePath);
    url.searchParams.set('utm_source', 'app');
    return url.toString(); 
}

大多数情况下都可以正常使用:

buildURL('search')
"http://example.com/search?utm_source=app"

buildURL('search?q=query&page=2')
"http://example.com/search?q=query&page=2&utm_source=app"

当我添加锚点时问题开始了:

buildURL('search#anchor')
"http://example.com/search?utm_source=app#anchor"

buildURL('search#anchor?q=query')
"http://example.com/search?utm_source=app#anchor?q=query"

这不是带锚的有效网址。

有关如何使用网址克服此问题的任何想法?

修改

预期结果是在锚

之后添加查询参数
 buildURL('search#anchor')
"http://example.com/search#anchor?utm_source=app"

buildURL('search#anchor?q=query')
"http://example.com/search#anchor?utm_source=app?q=query"

function buildURL(relativePath) {
    var url = new URL('http://example.com/' + relativePath);
    url.searchParams.set('utm_source', 'app');
    return url.toString(); 
}

console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));

2 个答案:

答案 0 :(得分:0)

不要在搜索参数中传入哈希值。

但如果必须,你可以检测哈希,从参数中分离,设置搜索参数并添加哈希



function buildURL(relativePath) {
    var hash = "";
    if (relativePath.indexOf("#")!=-1) {
      var parts = relativePath.split("#");
      hash = encodeURIComponent(parts[1]); // optionally handle ? in the hash part
      relativePath=parts[0];
    } 
    var url = new URL('http://example.com/' + relativePath);
    url.searchParams.set('utm_source', 'app');
    if (hash) url.hash=hash;
    return url.toString(); 
}

console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));




答案 1 :(得分:0)

这应该可以.. 在查询参数后传递哈希



function buildURL(path) {
  var relativePath = path.split('#')
  var url = new URL('http://example.com/' + relativePath[0]);
  url.searchParams.set('utm_source', 'app');
  url.hash = relativePath[1] ? relativePath[1] : ''
  return url.toString();
}

console.log(buildURL("search"));
console.log(buildURL("search?q=query&page=1"));
console.log(buildURL("search#anchor"));
console.log(buildURL("search#anchor?q=query"));
console.log(buildURL("searchr?q=query&q2=query2#anchor"));