Parse an URL in JavaScript

JavascriptJqueryParse Url

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - 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.

Solution 2 - Javascript

If your string is called s then

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

will give it to you.

Solution 3 - Javascript

Try this:

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

Solution 4 - Javascript

One liner:

location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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"

Solution 8 - Javascript

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"

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

Web Workers provide an utils URL for url parsing.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRunView Question on Stackoverflow
Solution 1 - JavascriptSindre SorhusView Answer on Stackoverflow
Solution 2 - JavascriptRay ToalView Answer on Stackoverflow
Solution 3 - JavascriptmdaguerreView Answer on Stackoverflow
Solution 4 - JavascriptIlya KharlamovView Answer on Stackoverflow
Solution 5 - JavascriptA. MassonView Answer on Stackoverflow
Solution 6 - JavascriptkobeView Answer on Stackoverflow
Solution 7 - JavascriptmichielbdejongView Answer on Stackoverflow
Solution 8 - JavascriptKevin CoxView Answer on Stackoverflow
Solution 9 - JavascriptMittal PatelView Answer on Stackoverflow
Solution 10 - JavascriptMd. Afsar UddinView Answer on Stackoverflow
Solution 11 - JavascriptMuhammad TahirView Answer on Stackoverflow
Solution 12 - JavascriptAndrei G.View Answer on Stackoverflow
Solution 13 - JavascriptfxpView Answer on Stackoverflow