extract GET parameters from a user inputed url with javascript
I am looking to use javascript to extract the GET para开发者_开发知识库meters from a user inputed url.
For example is a user enters a url say:
http://www.youtube.com/watch?v=ee925OTFBCA
I could get the v parameter
'ee925OTFBCA' as a variable
Thanks in Advance.
This should do the trick
// include this somewhere available
var Query = (function(){
var query = {}, pair, search = location.search.substring(1).split("&"), i = search.length;
while (i--) {
pair = search[i].split("=");
query[pair[0]] = decodeURIComponent(pair[1]);
}
return query;
})();
var v= Query["v"]
This only runs its computation once and creates an object with name/value pairs corresponding to those supplied as parameters
From here:
function getURLParam(strParamName){
var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (
aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
break;
}
}
}
return unescape(strReturn);
}
To use it:
var v = getURLParam('v')
You can use a function like this:
function querystring(key) {
var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
var r=[], m;
while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
return r;
}
Example:
var v = querystring('v')[0];
The function returns an array with all the values found in the query string. If you have a query string like ?x=0&v=1&v=2&v=3
the call querystring('v')
returns an array with three items.
This is my simple snippet:
function extractParamValue(url, name) {
var pos = url.indexOf(name+'=')+name.length+1;
var value = url.substring(pos, url.indexOf('&', pos));
return value;
}
精彩评论