Last active
August 29, 2015 13:56
-
-
Save roseforyou/9250413 to your computer and use it in GitHub Desktop.
get URL parameters, key and value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//URL: http://www.example.com/?var1=val1&var2=val2=val3&test=3&test=43&aaa=#2 | |
//window.location.search will return "?var1=val1&var2=val2=val3&test=3&test=43&aaa=" | |
//use the location.search, because # could be remove. | |
//refer: | |
//https://gist.github.com/alkos333/1771618 | |
//http://papermashup.com/read-url-get-variables-withjavascript/ | |
//http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html | |
//1. | |
//getUrlVars() will return {var1: "val1", var2: "val2=val3", test: "43", aaa: ""} | |
function getUrlVars() { | |
var vars = {}; | |
var parts = window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(match, key ,value) { | |
vars[key] = value; | |
}); | |
return vars; | |
} | |
//2. | |
//getUrlVars() will return array ["var1", "var2", "test", "test", "aaa"] | |
//getUrlvars('var2') will return "val2=val3" | |
function getUrlVars(key) { | |
var vars = []; | |
var parts = window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(match, key, value) { | |
vars.push(key); | |
vars[key] = value; | |
}); | |
if (key) { | |
return vars[key]; | |
} | |
return vars; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment