Query string substitutions for links on a page
The code you provide is inefficient in two ways:


Unnecessary loops. It loops through a.rewrite anchor each time for one querystring match. It could be optimized into one loop;
Repeated calculation on regular expression matches. regexS is executed for each gup function and it could be reduced into one calculation.


The solutions are:


Fetch the window.location.href data into one variable which could be referred to later;
Integrate the two (or more) loops into one and finish all the replacement in one loop.


Here the optimized code goes:

//First you fetch the query string as key-value pairs in the window.location.href, this equals your gup function.

//This code, fetch the ?key1=value1&amp;key2=value2 pair into an javaScript Object {'key1': 'value1', 'key2':'value2'}
var queryString = {}; 
var queryStringPattern = new RegExp("([^?=&amp;]+)(=([^&amp;]*))?", "g");
window.location.href.replace(
    queryStringPattern,
    function($0, $1, $2, $3) { queryString[$1] = $3; }
);

//Second you collect all the anchor with class rewrite and execute the replacement.

$("a.rewrite").each(function () {
  this.href.replace(
    queryStringPattern,
    function ($0, $1, $2, $3) {
      return queryString[$1] ? $1 +  "=" + queryString[$1] : $1 + '=' + $3;
    }
  )
});