Parse an URL in JavaScript

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://example.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.


If your string is called s then

var id = s.match(/img_id=([^&]+)/)[1]

will give it to you.