要在单个正则表达式中获取查询字符串,请使用:
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"