2014-10-19 94 views
0

完整的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參數並將名稱插入頁面上的幾個字段。這就是爲什麼我需要讀取完整參數,包括散列標籤,因此它在頁面上正確顯示。

+0

從否定的字符集刪除''#? – hjpotter92 2014-10-19 23:10:45

+0

@ hjpotter92 - 可能,但我正在尋找一種方法,讓它儘可能地在那裏。 – L84 2014-10-19 23:12:20

+2

你能解釋一下你的意思嗎?如果要匹配參數直到字符串結尾,請嘗試'(。+?(?:&| $))' – hjpotter92 2014-10-19 23:16:27

回答

0

此答案的榮譽屬於@ 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'))); 
0

這是否適合您?

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

小提琴http://jsfiddle.net/xvgs6r38/3/