在JavaScript中解析URL

时间:2011-07-11 00:22:02

标签: javascript jquery parse-url

如何使用JavaScript解析URL(也使用jQuery)?

例如我在我的字符串中有这个,

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

我想获得img_id

的值

我知道我可以使用PHP parse_url()轻松完成此操作,但我想知道如何使用JavaScript。

13 个答案:

答案 0 :(得分:119)

您可以使用创建a - 元素的技巧,添加网址,然后使用其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

将输出:?img_id=33


您还可以使用php.js获取parse_url function in JavaScript


更新(2012-07-05)

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

答案 1 :(得分:35)

如果您的字符串被称为s,那么

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

会给你。

答案 2 :(得分:10)

试试这个:

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

答案 3 :(得分:6)

现有的优秀jQuery插件Purl (A JavaScript URL parser)。这个实用程序有两种使用方式 - 使用jQuery或不使用...

答案 4 :(得分:5)

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

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

答案 5 :(得分:5)

一个班轮:

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

答案 6 :(得分:3)

这应该在kobe的答案中解决一些边缘案例:

<html>
<head>
<style type="text/css">
#content {

width: 980px;
height: 500px;
padding: 20 20 20 20;
background-color: #00fcff }
#package_update {

width: 680;
height: 500;
float: left;
background-color: #aaaaaa }
#previous_update {

width: 280;
height: 500;
float: right;
background-color: #ffcc00 }
</style>
</head>
<body>
<div id="content">

<div id="package_update"></div>
<div id="previous_update"></div>

</div>
</body>
</html>

答案 7 :(得分:2)

我写了一个javascript url解析库URL.js,您可以将它用于此。

示例:

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

答案 8 :(得分:2)

这样的事情对你有用。即使有多个查询字符串值,此函数也应返回所需键的值。

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

答案 9 :(得分:1)

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

答案 10 :(得分: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

答案 11 :(得分:1)

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

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

答案 12 :(得分:0)

Web Workers提供了URL来进行URL解析。