如何获取查询字符串中包含的URL

时间:2013-05-01 06:16:43

标签: javascript html url get

我想要一个javascript变量是url中的url =背后的内容..

例如:当前网址是

http://mywebsite.com/test/index.html?url=http://www.google.com/

所以变量必须是http://www.google.com/

我尝试了这个,但它不起作用......为什么?

    var url = document.URL ;
    var appname = url.match(?url=(.+))[1];

感谢。

3 个答案:

答案 0 :(得分:2)

我认为以下内容适合您:

function querystring(key) {
    var query = window.location.search.substring(1);
    var keys = query.split("&");
    for (i = 0; i < keys.length; i++) {
        var values = keys[i].split("=");
        if (values[0] == key) {
            return values[1];
        }
    }
}
var appname = querystring("url");
alert(appname);

答案 1 :(得分:1)

试试这个:

var regex = /\?url\=(.+)/;
var appname = regex.exec(url)[1];

甚至更简单:

var appname = /\?url\=(.+)/.exec(url)[1];

答案 2 :(得分:1)

var url = location.search.match(/url=([^&]+)&*.*$/)[1]; // http://www.google.com/

location     //location object
 .search     //the search part in location
 .match      //return string according to regex given
  [1]        //second result (result in parenthesis)

//--------Use in a function---------

function getQuery(txt){
    var result = location.search.match(new RegExp(txt + "=([^&]+)&*.*$"));
    return result === null ? undefined : result[1];
}

http://jsfiddle.net/DerekL/J4FfZ/