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 = "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.

155674 次浏览

If your string is called s then

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

will give it to you.

Try this:

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

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

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.

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

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"

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

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

One liner:

location.search.replace('?','').split('&').reduce(function(s,c){var t=c.split('=');s[t[0]]=t[1];return s;},{})
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

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"
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

Web Workers provide an utils URL for url parsing.