If the current page URL has an argument ‘myid1’ 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 following code:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript">
$(function() {
var requestid = new String(gup('myid1'));
if (requestid!=null&&requestid!="") {
$("a.rewrite").each(function() {
var href = $(this).attr("href");
href += "?myid1=" + requestid;
$(this).attr("href", href);
})
}
})
//gup taken from here:http://www.netlobo.com/url_query_string_javascript.html
function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
</script>
<a href="http://www.otherdomain.com?someid=1234" class="rewrite">Hyperlink</a>
The problem is that the URS’s querystring is being added to the links without removing the existing one. How to fix it?
Also, how do I allow one more parameter called ‘myid2’. Thank you in advance for your help.
You can remove a prefious query string with this:
Several things to note in this revision:
if (requestid)tests fornull,undefinedand""so you can use just the one test.hrefattribute. It’s faster and more direct to just usethis.href.If you like fewer lines of code (though not quite as fast), you would do it this way: