title: How to properly add search query param to url containing hash in javascript?
body: <p>I want to add a base url and query parameters to each link:</p>
  
  <pre><code>function buildURL(relativePath) {
      var url = new URL('http://example.com/' + relativePath);
      url.searchParams.set('utm_source', 'app');
      return url.toString(); 
  }
  </code></pre>
  
  <p>It works fine for most cases:</p>
  
  <pre><code>buildURL('search')
  "http://example.com/search?utm_source=app"
  
  buildURL('search?q=query&amp;page=2')
  "http://example.com/search?q=query&amp;page=2&amp;utm_source=app"
  </code></pre>
  
  <p>The problem starts when I add an anchor:</p>
  
  <pre><code>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"
  </code></pre>
  
  <p>This is not a valid URL with an anchor. </p>
  
  <p><strong>Any ideas on how to overcome that using URL?</strong></p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The expected outcome is adding the query params <em>after</em> the anchor</p>
  
  <pre><code> 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"
  </code></pre>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>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&amp;page=1"));
  console.log(buildURL("search#anchor"));
  console.log(buildURL("search#anchor?q=query"));</code></pre>
  </div>
  </div>
  </p>