Query string substitutions for links on a page If the current page URL has an argument 'myid1' or 'myid2' in the querystring, for each link in my webpage with class 'rewrite', I want the link href's querystring to be replaced by the current page URL's querystring. I'm using the code given below. Since I'm new to javascript, I'm not sure if its optimized. I want it to execute as fast as possible. 

&lt;script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'&gt;&lt;/script&gt;

&lt;script type="text/javascript"&gt;
$(function() {
    var requestid = gup('myid1');
    if (requestid) {
        $("a.rewrite").each(function() {
            var base = this.href;
            var pos = base.indexOf("?");
            if (pos != -1) {
                base = base.substr(0, pos);
            }
            this.href = base + "?myid1=" + requestid;
        })
    }
    var requestid2 = gup('myid2');
    if (requestid2) {
        $("a.rewrite").each(function() {
            var base = this.href;
            var pos = base.indexOf("?");
            if (pos != -1) {
                base = base.substr(0, pos);
            }
            this.href = base + "?myid2=" + requestid2;
        })
    }
})

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&amp;]"+name+"=([^&amp;#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
&lt;/script&gt;

&lt;a href="http://www.website.com/?someid=1234" class="rewrite"&gt;Hyperlink&lt;/a&gt;
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;
    }
  )
});