Parse an URL in JavaScript

How do I parse an URL with JavaScript (also with jQuery)?

For instance I have this in my string,

url = ""

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 how it is possible with 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;


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.


Existing good jQuery plugin Purl (A JavaScript URL parser).This utility can be used in two ways - with jQuery or without...


One liner:'?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})

got it from google, try to use this method

function getQuerystring2(key, default_) 
    if (default_==null) 
    var search = unescape(; 
    if (search == "") 
        return default_; 
    search = search.substr(1); 
    var params = search.split("&"); 
    for (var i = 0; i < params.length; i++) 
        var pairs = params[i].split("="); 
        if(pairs[0] == key) 
            return pairs[1]; 

return default_; 

This should fix a few edge-cases in kobe's answer:

function getQueryParam(url, key) {
  var queryStartPos = url.indexOf('?');
  if (queryStartPos === -1) {
  var params = url.substring(queryStartPos + 1).split('&');
  for (var i = 0; i < params.length; i++) {
    var pairs = params[i].split('=');
    if (decodeURIComponent(pairs.shift()) == key) {
      return decodeURIComponent(pairs.join('='));

getQueryParam('', 'img_id');
// outputs "33"

I wrote a javascript url parsing library, URL.js, you can use it for this.


url.parse("").get.img_id === "33"

You can use the jquery plugin $.url("?img_id") will return 33


Web Workers provide an utils URL for url parsing.


Try this:

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Something like this should work for you. Even if there are multiple query string values then this function should return the value of your desired key.

function getQSValue(url) 
    key = 'img_id';
    query_string = url.split('?');
    string_values = query_string[1].split('&');
    for(i=0;  i < string_values.length; i++)
        if( string_values[i].match(key))
            req_value = string_values[i].split('=');    
    return req_value[1];
function parse_url(str, component) {
  //       discuss at:
  //      original by: Steven Levithan (
  // reimplemented by: Brett Zamir (
  //         input by: Lorenzo Pisani
  //         input by: Tony
  //      improved by: Brett Zamir (
  //             note: original by
  //             note: blog post at
  //             note: demo at
  //             note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
  //             note: a seriously malformed URL.
  //             note: Besides function name, is essentially the same as parseUri as well as our allowing
  //             note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
  //        example 1: parse_url('http://username:[email protected]/path?arg=value#anchor');
  //        returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}

  var query, key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',
      'relative', 'path', 'directory', 'file', 'query', 'fragment'
    ini = (this.php_js && this.php_js.ini) || {},
    mode = (ini['phpjs.parse_url.mode'] &&
      ini['phpjs.parse_url.mode'].local_value) || 'php',
    parser = {
      php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))[email protected])?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))[email protected])?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))[email protected])?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)

  var m = parser[mode].exec(str),
    uri = {},
    i = 14;
  while (i--) {
    if (m[i]) {
      uri[key[i]] = m[i];

  if (component) {
    return uri[component.replace('PHP_URL_', '')
  if (mode !== 'php') {
    var name = (ini['phpjs.parse_url.queryKey'] &&
      ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
    parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
    uri[name] = {};
    query = uri[key[12]] || '';
    query.replace(parser, function($0, $1, $2) {
      if ($1) {
        uri[name][$1] = $2;
  delete uri.source;
  return uri;


var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]

Worked for me. But the first var should be var url = window.location.href


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.