2012-07-20 77 views

回答

417
function getURLParameter(name) { 
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null; 
} 

所以,你可以使用:

myvar = getURLParameter('myvar'); 
+1

感謝偉大的答案。增加了對其的編輯,以考慮沒有值的參數的邊緣情況。 – nicolaslara 2014-05-27 10:35:17

+3

@DeanMeehan真棒如果它「只是工作」,但我不會說這是一個簡單的解決方案,考慮到正則表達式的可讀性 – 2014-10-30 14:59:50

+3

這是否工作,如果在URI中有一個哈希標籤?如果在Chrome中有'#something',那麼你必須使用'window.location.hash'而不是'window.location.search' ... – 2015-01-08 21:54:44