问题
Possible Duplicate:
Get query string values in JavaScript
I am working on a extension for Chrome. I already figured out how to get the URL from the actual Chrome-Tab.
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
But now i need to know how to get a specific Parameter from the URL. I already tried out different Javascript-Functions but when i implement them, my Extension stops working.
So: How can i get a specific parameter from the actual URL?
回答1:
To get a query string in a single regexp, use:
var queryString = /^[^#?]*(\?[^#]+|)/.exec(tab.url)[1];
// Explanation of RegEx:
// ^[^#?]* (\?[^#]+ | )
// <Starts with any non-#/? string><query string OR nothing>
Then, use the following function to get the value of a specific key:
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"
回答2:
Not exactly a regex, but this should work:
var queryString=url.match(/\?.+$)[0].split('#')[0]
This should work in most cases. I'll try to dig up the regex I had written for this some time ago.
回答3:
Created simple function to get URL parameter in Javascript from a URL like this
.....58e/web/viewer.html?page=17&getinfo=33
function buildLinkb(param) {
var val = document.URL;
var url = val.substr(val.indexOf(param))
var n=parseInt(url.replace(param+"=",""));
alert(n+1);
}
buildLinkb("page");
OUTPUT : 18
来源:https://stackoverflow.com/questions/11773190/chrome-extension-get-parameter-from-url