Possible Duplicate:
Get query string values in JavaScript
我正在为 Chrome 开发一个扩展程序。
我已经想出如何从实际的 Chrome-Tab 获取 URL。
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
但现在我需要知道如何从 URL 中获取特定参数。
我已经尝试过不同的 Javascript 函数,但是当我实现它们时,我的扩展停止工作。
所以:
如何从实际 URL 中获取特定参数?
要在单个正则表达式中获取查询字符串,请使用:
var queryString = /^[^#?]*(\?[^#]+|)/.exec(tab.url)[1];
// Explanation of RegEx:
// ^[^#?]* (\?[^#]+ | )
// <Starts with any non-#/? string><query string OR nothing>
然后,使用以下函数获取特定键的值:
function getParameterByName(queryString, name) {
// Escape special RegExp characters
name = name.replace(/[[^$.|?*+(){}\\]/g, '\\$&');
// Create Regular expression
var regex = new RegExp("(?:[?&]|^)" + name + "=([^&#]*)");
// Attempt to get a match
var results = regex.exec(queryString);
return decodeURIComponent(results[1].replace(/\+/g, " ")) || '';
}
// Usage:
// Example: tab.url = "http://example.com/path?foo=bar&key_name=qs_value#"
var queryString = /\?[^#]+(?=#|$)|$/.exec(tab.url)[0];
var value = getParameterByName(queryString, 'qs_name');
// Result : value = "value";
// Example 2: Using the function to get a parameter from the current page's URL.
// (e.g inside content script)
var value = getParameterByName(location.search, 'qs_name');
// Result : value = "value"