title: How can I replace a segment of the URL and reload the page?
body: <p>I need to write a script for Greasemonkey that will check the URL, replace a section of it when certain conditions are met, and reload the page.</p>
  
  <p>The URLs in question will always be in this format:</p>
  
  <p><a href="https://optionA.example.com/ab/first/second/tonsOfMetadata" rel="nofollow noreferrer">https://optionA.example.com/ab/first/second/tonsOfMetadata</a> </p>
  
  <p><a href="https://optionB.example.com/ab/first/second/tonsOfMetadata" rel="nofollow noreferrer">https://optionB.example.com/ab/first/second/tonsOfMetadata</a></p>
  
  <p>I need the script to check for the "first/second" segment and then replace it with "third/fourth." These will always be the same. The only thing that will change from URL to URL is the metadata and the subdomain which will either be A or B.</p>
  
  <p>This is the code I'm trying to get working:</p>
  
  <pre><code>var url = window.location.host; 
  var regex = /^(https?:\/\/)([^.]+\.)(example\.com\/ab\/)first\/second(\/.+)$/i;
  
  if (url.match(regex) != null){
  url = window.location.href;
  url = url.replace(regex,"$1$2$3third/fourth$4");
      return;
  }
  
  console.log(url);
  window.location.replace(url);
  }
  </code></pre>
  
  <p>I'm sure I'm missing something obvious, but my experience with coding is limited. I've adapted the code from here: <a href="https://stackoverflow.com/questions/24984576/replace-parts-of-a-url-in-greasemonkey">Replace parts of a URL in Greasemonkey</a> and from here: <a href="https://stackoverflow.com/questions/3232992/rewrite-parts-of-a-url-in-greasemonkey-and-firefox">Rewrite parts of a URL in Greasemonkey and FireFox</a>.</p>
  
  <p>Any help will be much appreciated, thanks in advance!</p>