Carter Bailey Tech Thoughts, lessons learned, and motivation

26Oct/122

Quick Simple (and kinda dirty) URL Manipulation with JavaScript/jQuery

This is probably not something unfamiliar to you, maybe you've done it before or maybe you think this is the dumbest way to do this ever.

I thought it was pretty nifty (the wonders of JavaScript and jQuery never end), and I thought I'd share.

1
2
3
4
$('a').attr('href',
  function () {
    return this + '&AdditionalQueryVar=newvalue';
});

Click through to let me know in the comments what you think and what you would do for this.

[Updated 25 April 2013: Commenter Mike made a suggested rewrite for this snippet and has a great little URL manipulation library available on GitHub: https://github.com/Mikhus/jsurl]

That's it. Simple right?

All I needed/wanted to do is add the necessary Query String variable to the end of necessary links on the page when the page is loaded and dynamically filled out. There's probably an easier way, but this was the 5-minute "ah-ha!" fix, and I'm sticking to it!

Let me know how you'd do it down in the comments.

Carter

EDIT:

Originally, I hadn't taken into account the addition of multiple querystring parameters, and user Mike made the following rewrite to improve on the above snippet.

1
2
3
4
5
6
$('a').attr('href',
  function() {
    var u = new Url(this);
    u.query.AdditionalQueryVar = 'newvalue';
    return u;
});

Mike also has a small URL manipulation library available on GitHub if you need solve any problems with URL manipulation!
https://github.com/Mikhus/jsurl

Posted by Carter Bailey

Filed under: Code Leave a comment
Comments (2) Trackbacks (0)
  1. What to do if current URL of the link does not contain any QueryString parameters yet? You need to take care about “?” character, because URL can be broken. Then you need to take care not to add implicitly your params several times (if current URL already contains those params you need to replace them or just not to add), etc…

    I did small library which helps to solve all the problems with URLs manipulation. You can get it here – https://github.com/Mikhus/jsurl

    So your solution could be rewritten like this:

    $a(‘a’).attr( ‘href’, function() {
    var u = new Url(this);
    u.query.AdditionalQueryVar = ‘newvalue’;
    return u;
    });

    • Hi Mike, and thanks for the suggestion! I had come across this issue and had modified our working code to deal with this. I just hadn’t made any updates to this post :-/ (plus, your suggestion is better than what I had done!)

      I will definitely add your suggested lib and rewritten solution to the post :)


Leave a Reply to Carter Bailey Cancel reply

No trackbacks yet.