77

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

For instance I have this in my string,

url = "http://example.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 how it is possible with JavaScript.

Karol Selak
  • 4,248
  • 6
  • 35
  • 65
Run
  • 54,938
  • 169
  • 450
  • 748
  • 5
    With php you dont need to use the parse_url() function to get the img_id, just use $_GET['img_id] – mdaguerre Jul 11 '11 at 00:28
  • 2
    possible duplicate of [Get query string values in JavaScript](http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript) – alex Jul 11 '11 at 00:51
  • 2
    The correct answer below is totally ridiculous when all you need is `window.location.search.split('=')[1]`. I can't believe he got 75 votes for that!! – Adam Spence Sep 29 '14 at 11:32
  • 3
    @AdamSpence window.location only works for the page url, not an arbitrary url string. – Fraser Harris Nov 23 '14 at 23:32

13 Answers13

123

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.

congusbongus
  • 13,359
  • 7
  • 71
  • 99
Sindre Sorhus
  • 62,972
  • 39
  • 168
  • 232
  • 4
    Which is equivalent to `url.match(/\?.+/)[0]`, which is somewhat shorter and likely a lot faster. – RobG Jul 11 '11 at 06:09
  • Sure, it might have somewhat of an overhead, but it's not using regex and you can do a lot more with the Location object. – Sindre Sorhus Jul 11 '11 at 10:15
  • 9
    wow, never knew about this trick, it made my day after sorting through all the worlds ugliest regular expressions =) – Greg Guida Jul 28 '11 at 18:34
  • @SindreSorhus I followed your link, but it doesn't say that you can use the search property on an anchor tag...? – Christophe May 31 '12 at 15:42
  • 2
    @Christophe No it shows you what properties are available. When you assign an url to the href property of an anchor element, it get's all the properties of the Location object. – Sindre Sorhus May 31 '12 at 21:30
  • 1
    @SindreSorhus Amazing! Could you share a reference that explains it and details browser support? Is this also true for elements that have a src attribute (link, iframe)? – Christophe May 31 '12 at 22:19
  • I found some more information on http://help.dottoro.com/ljneplda.php. It seems that all browsers support pathname, search, etc. on anchors. Elements like link only support some of them – Christophe May 31 '12 at 22:48
  • +1 for URI.js which is really awesome for a price of ~21kB in it's simplest version (base lib only). – skalee Jan 04 '13 at 17:09
  • On IE 7 and above it will fail to parse URL with HTTP Basic Auth credentials. – Adi Roiban Feb 04 '14 at 09:56
  • 1
    window.location.search – Adam Spence Sep 29 '14 at 11:35
  • To get pathname, search, hash from string url, use https://developer.mozilla.org/en-US/docs/Web/API/URL. – MCFreddie777 Aug 16 '21 at 08:03
36

If your string is called s then

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

will give it to you.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
10

Try this:

var url = window.location;
var urlAux = url.split('=');
var img_id = urlAux[1]
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
mdaguerre
  • 1,237
  • 1
  • 10
  • 22
7

One liner:

location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})
Ilya Kharlamov
  • 3,698
  • 1
  • 31
  • 33
6

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

A. Masson
  • 2,287
  • 3
  • 30
  • 36
4

got it from google, try to use this method

function getQuerystring2(key, default_) 
{ 
    if (default_==null) 
    { 
        default_=""; 
    } 
    var search = unescape(location.search); 
    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_; 
}
kobe
  • 15,671
  • 15
  • 64
  • 91
  • 2
    This will fail if the value of a query parameter contains '%3D' ('=') or '%26' ('&'). To fix, use this inside the for loop: ```` if (pairs.shift() == key) { return pairs.join('='); } ```` and do the unescape after splitting on '&'. – michielbdejong Jan 05 '16 at 15:29
3

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

function getQueryParam(url, key) {
  var queryStartPos = url.indexOf('?');
  if (queryStartPos === -1) {
    return;
  }
  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('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"
michielbdejong
  • 1,077
  • 9
  • 14
2

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

Example:

url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33"
Kevin Cox
  • 3,080
  • 1
  • 32
  • 32
  • No, I've never heard of purl.js berfore. – Kevin Cox Nov 26 '13 at 00:14
  • The answer just above yours. Your code is 28 times faster and much cleaner than purl, but I cannot use it in its current state. I've created an issue on github for you to look at. Thank you – Steven Vachon Nov 26 '13 at 02:50
  • 2
    You are just forgetting to run the build step. However the new version doesn't require the build step any more so there is no need to worry about it now :D – Kevin Cox Nov 26 '13 at 16:40
2

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];
}
Mittal Patel
  • 806
  • 6
  • 8
1

You can use the jquery plugin http://plugins.jquery.com/url. $.url("?img_id") will return 33

1
function parse_url(str, component) {
  //       discuss at: http://phpjs.org/functions/parse_url/
  //      original by: Steven Levithan (http://blog.stevenlevithan.com)
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //         input by: Lorenzo Pisani
  //         input by: Tony
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //             note: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: blog post at http://blog.stevenlevithan.com/archives/parseuri
  //             note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             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:password@hostname/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: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\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_', '')
      .toLowerCase()];
  }
  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;
}

reference

Muhammad Tahir
  • 2,351
  • 29
  • 25
1
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

Andrei G.
  • 151
  • 3
  • 5
0

Web Workers provide an utils URL for url parsing.

fxp
  • 6,792
  • 5
  • 34
  • 45