Pull包含哈希标记的完整URL参数



我有一个URL,看起来像这样:

example.com/puppy-reservation?puppy=Bitzy's Female #1

我需要读取整个URL参数。我尝试使用以下脚本:

$.urlParam = function(name){
    var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}
console.log(decodeURIComponent($.urlParam('puppy'))); 

当它运行时,它会给我Bitzy's Female

如何修改脚本以读取整个URL参数?IE:Bitzy's Female #1

进一步解释。我的CMS正在输出数据库条目的名称。在这种情况下,它是Bitzy's Female #1。这就是它进入CMS的方式。在页面上,用户可以单击您在上面看到的URL:example.com/puppy-reservation?puppy=Bitzy's Female #1

当页面加载时,我读取URL参数,并将名称插入页面上的几个字段中。这就是为什么我需要读取完整的参数,包括hash标记,以便它在页面上正确显示。

这对你有用吗?

var url = window.location.href;
url = encodeURIComponent(url).split(encodeURIComponent('?'))[1];
var obj = {};
if (url) {
    url = url.split(encodeURIComponent('&'));
    for (var i = 0; i < url.length; i++) {
       var param = url[i].split(encodeURIComponent('='));
       obj[decodeURIComponent(param[0])] = decodeURIComponent(param[1]);
    }
}
console.log(obj);

Fiddlehttp://jsfiddle.net/xvgs6r38/3/

这个答案归功于@hjpotter92。自从他在评论中留下后,我就把它贴在这里了。

在我的代码中,我有以下行:

var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);

如果我将=([^&#]*)')更改为=(.+?(?:&|$))'),它就起作用了。

完整代码:

$.urlParam = function(name){
    var results = new RegExp('[?&]' + name + '=(.+?(?:&|$))').exec(window.location.href);
    if (results==null){
       return null;
    }
    else{
       return results[1] || 0;
    }
}
console.log(decodeURIComponent($.urlParam('puppy'))); 

最新更新