joshcomley
joshcomley

Reputation: 28838

Is there a simple JavaScript way to manipulate arbitrary URLs?

Is there a way to easily handle manipulating URLs in JavaScript?

A bit of context:

I want to use ThickBox, the popular jQuery modal popup box, but unobtrusively. According to the ThickBox documentation I have to give all links that I want to be made modal a CSS class of "thickbox" and change the URL from...

http://www.mysite.com/mypopup

...to:

http://www.mysite.com/mypopup?height=200&width=300

I want to make this happen only if JavaScript is enabled.

So I get all links using jQuery and "hack" a detect for the '?' character in the URL, appending "&height..." or "?height..." accordingly.

In the grander scheme of things, this might muddle stuff up if the URL already has a "height" parameter, in which case I might just want to update the existing one as opposed to give it two.

It all smells a little.

I feel like I'm hacking code that can/must have been done properly once already!

So my question is:

Is there something in the JavaScript world (plugin or not) that would enable me to something like this:

var url = Url(elm.attr("href"));
url.parameter("width", "300");
url.parameter("height", "200");
elm.attr("href", url.toString())

Or:

var height = Url(elm.attr("href")).parameter("height");

Upvotes: 2

Views: 378

Answers (3)

karim79
karim79

Reputation: 342755

This function does that, just call it on the page of the URL you want to parse:

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];
}

//for the URL http://www.mysite.com/mypopup?height=200&width=300

var height = gup( 'height' );
var width = gup('width');
alert('Height: ' + height + ' Width: ' + width);

EDIT: I don't know how useful this will be to use (as it uses Prototype.js) but this is for reading and modifying the query string:

http://code.nontalk.com/2006/10/readmodify-querystring-variables-with.html

Upvotes: 1

Lazarus
Lazarus

Reputation: 43114

You can probably do that using jQuery, i.e.

$(".thickbox").each(function() {
  this.href += "?height=200&width=300";
});

I've not tested this and it may be wrong, I'm not in a position to test it at the moment but hopefully it'll point you in the right direction if nothing else. If you have jQuery for Thickbox then you may as well leverage it for the manipulation ;)

Upvotes: 0

peirix
peirix

Reputation: 37771

Yes. The location Object in javascript has quite a lot of properties.

For your question: location.search = "width=300"; would apply "?width=300" to your url.

Upvotes: 0

Related Questions