在JavaScript中parsingURL

如何用JavaScriptparsingURL(也用jQuery)?

比如我在我的string中有这个,

url = "http://example.com/form_image_edit.php?img_id=33" 

我想获得img_id的值

我知道我可以使用parse_url()方便地执行此操作,但是我想知道如何使用JavaScript。

您可以使用创builda元素的技巧,将url添加到它,然后使用它的Location对象 。

 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 

将输出: ?img_id=33


你也可以使用php.js来获取JavaScript中的parse_url函数 。


更新(2012-07-05)

我会build议使用优秀的URI.js库,如果你需要做的不只是超级简单的URL处理。

如果你的string被称为s然后

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

会把它给你。

尝试这个:

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

现有良好的jQuery插件Purl(一个JavaScript URLparsing器) 。该实用程序可以以两种方式使用 – 与jQuery或没有…

从谷歌得到它,尝试使用这种方法

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

一个class轮:

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

我写了一个javascript urlparsing库, URL.js ,你可以用它来做这个。

例:

 url.parse("http://mysite.com/form_image_edit.php?img_id=33").get.img_id === "33" 

像这样的东西应该为你工作。 即使有多个查询string值,那么这个函数应该返回你想要的键的值。

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

你可以使用jquery插件http://plugins.jquery.com/url$.url("?img_id")将返回33

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

参考

这应该在科比的答案中解决一些边缘情况:

 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] 

为我工作。 但第一个变种应该是var url = window.location.href