teelou teelou - 6 months ago 32
Javascript Question

Parse URL with jquery/ javascript?

How do I parse an url with jquery/ javascript?

For instance I have this in my string,

http://mysite.com/form_image_edit.php?img_id=33


I want to get the value of
img_id


I know I can do this easily with php with
parse_url()
, but I want to know if it is possible with javascrip.

Answer

You can use a trick of creating an a-element, add the url to it, and then use its Location object.

function parseUrl( url ) {
    var a = document.createElement('a');
    a.href = url;
    return a;
}

parseUrl('http://mysite.com/form_image_edit.php?img_id=33').search

Which will output: ?img_id=33


You could also use php.js to get the parse_url function in JavaScript.


Update (2012-07-05)

I would recommend using the excellent URI.js library if you need to do anything more than super simple URL handling.

Comments