In Javascript, how can I get the parameters of a URL string (not the current URL)?
http://localhost:8080/feasthunt/changePassword.html?TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED
can i get token in JSON object?
No need for a 'JSON' object, and just use split to grab it, since its after a '='
var url = 'http://localhost:8080/feasthunt/changePassword.html? TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED';
var token = url.split('=').pop();
//token is equal to: "0FA3267F-0C62-B1C9-DB71-76F6829671ED"
https://jsbin.com/siyazo/1/edit?js,console
try this
var str = "http://localhost:8080/feasthunt/changePassword.html?TOKEN=0FA3267F-0C62-B1C9-DB71-76F6829671ED";
var tokenValue = str.substring(str.indexOf("?")+1).split("=")[1];
Or more generic
var paramMap = {}; str.substring(str.indexOf("?")+1).split("&").forEach(function(val){
var param = val.split("=");
paramMap[param[0]] = param[1];
})
paramMap is your JSON object, where paramMap["TOKEN"] will give you the value for this param
Related
This question already has answers here:
Get the values from the "GET" parameters (JavaScript) [duplicate]
(63 answers)
How can I convert a comma-separated string to an array?
(19 answers)
How to obtain the query string from the current URL with JavaScript?
(19 answers)
Closed 4 years ago.
I have put an array into my URL like this:
var params = arrayitems.join('&');
var url = "https://www.example.com/page?="+params;
So the URL looks like this:
https://www.example.com/page?=item1&item2&item3&item4&item5
Now does anyone know how I can then put these items back into an array on the next page?
Thanks!
You can split them back by page?= and than &
let arrayitems = ['item1','item2','item3','item4','item5']
var params = arrayitems.join('&');
var url = "https://www.example.com/page?="+params;
let arrayBack = url.split('page?=')[1].split('&')
console.log(arrayBack)
URL Object:
Use URL to get the data you need from the search parameters.
URL is used to parse, construct, normalise, and encode URLs.
The URL object has a very convenient method called searchParams
The searchParams readonly property of the URL interface returns a
URLSearchParams object allowing access to the GET decoded query
arguments contained in the URL.
Quick solution:
not recommended... but works
Since your query parameters are not valid (no key, just values) an extra step is required to get the values.
const url = new URL('https://www.example.com/page?=item1&item2&item3&item4&item5');
const res = [...url.searchParams]
.flat()
.filter(v=>v!==null&&v.length>0);
console.log(res);
Better solution using valid URL:
It would be better if you instead organised your URL the following way, so that your url string would look like
https://www.example.com/page?item=item1&item=item2&item=item3
const params = ['item1','item2','item3']
.map(v=>'item='+v)
.join('&');
const urlStr = "https://www.example.com/page?"+params;
const url = new URL(urlStr);
//Two possible ways of getting the values
//Option 1
const resOption1 = url.searchParams.getAll('item');
//Option 2
const resOption2 = [...url.searchParams.values()];
console.log(resOption1);
console.log(resOption2);
JavaScript:
// Create the object which is an array
var output = new objPropertyAndValues;
var TempArray=[]; // blank array
// Lets grab the URL (windows.location.href)
var url_string = window.location.href;
var url = new URL(url_string);
//We now have URL as an object to read from.
//Lets turn the searchParams into a string which we can then split into an Array
var urlParamsString = url.searchParams.toString();
//Now lets split urlParamsString into an array
var AllParamsFound = urlParamsString.split("&");
// Lets read each array item by doing a loop
// We then split the array item value by the "=" sign to split parameter and value
for (i = 0; i < AllParamsFound .length; i++){
TempArray= AllParamsFound [i].split("=");
output.Property[i] = TempArray[0];
output.Value[i] = TempArray[1];
}
console.log(output);
//We allow an object to be created.
function objPropertyAndValues(){
this.Property = [];
this.Value = [];
}
Running Example:
// Create the object which is an array
var output = new objPropertyAndValues;
var TempArray=[]; // blank array
// Lets grab the URL (windows.location.href)
var url_string = "http://www.google.com?myName=Datacure&AnswerID=54379924&Likes=Pizza";
var url = new URL(url_string);
//We now have URL as an object to read from.
//Lets turn the searchParams into a string which we can then split into an Array
var urlParamsString = url.searchParams.toString();
//Now lets split urlParamsString into an array
var AllParamsFound = urlParamsString.split("&");
// Lets read each array item by doing a loop
// We then split the array item value by the "=" sign to split parameter and value
for (i = 0; i < AllParamsFound .length; i++){
TempArray= AllParamsFound [i].split("=");
output.Parameter[i] = TempArray[0];
output.Value[i] = TempArray[1];
}
// Example output
console.log (output.Value[0] + " should get " + output.Value[2] + " for answering question id: " + output.Value[1]);
// View the array
console.log(output);
//We allow an object to be created.
function objPropertyAndValues(){
this.Parameter = [];
this.Value = [];
}
I want to filter out a specific parameter out of the URL. I have the following situation:
The page got loaded (for example: http://test.com/default.aspx?folder=app&test=true)
When the page is loaded a function is called to push a entry to the history (pushState): ( for example: http://test.com/default.aspx?folder=app&test=true&state=1)
Now I want to call a function that reads all the parameters and output all these parameters expect for the state. So that I end up with: "?folder=app&test=true" (just a string value, no array or object). Please keep in mind that I do not know what all the names of the parameters are execpt for the state parameter
What I have tried
I know I can get all the parameters by using the following code:
window.location.search
But it will result in:
?folder=app&test=true&state=1
I try to split the url, for example:
var url = '?folder=app&test=true&state=1';
url = url.split('&state=');
console.log(url);
But that does not work. Also because the state number is dynamic in each request. A solution might be remove the last parameter out of the url but I also do not know if that ever will be the case therefore I need some filtering mechanisme that will only filter out the
state=/*regex for a number*/
To achieve this you can convert the querystring provided to the page to an object, remove the state property of the result - assuming it exists - then you can convert the object back to a querystring ready to use in pushState(). Something like this:
var qsToObj = function(qs) {
qs = qs.substring(1);
if (!qs) return {};
return qs.split("&").reduce(function(prev, curr, i, arr) {
var p = curr.split("=");
prev[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
return prev;
}, {});
}
var qs = '?'; // window.location.search;
var obj = qsToObj(qs);
delete obj.state;
console.log(obj);
var newQs = $.param(obj);
console.log(newQs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Credit to this answer for the querystring to object logic.
I would agree with Rory's answer, you should have an object to safely manipulate params. This is the function that I use.
function urlParamsObj(source) {
/* function returns an object with url parameters
URL sample: www.test.com?var1=value1&var2=value2
USE: var params = URLparamsObj();
alert(params.var2) --> output: value2
You can use it for a url-like string also: urlParamsObj("www.ok.uk?a=2&b=3")*/
var urlStr = source ? source : window.location.search ? window.location.search : ""
if (urlStr.indexOf("?") > -1) { // if there are params in URL
var param_array = urlStr.substring(urlStr.indexOf("?") + 1).split('&'),
theLength = param_array.length,
params = {},
i = 0,
x;
for (; i < theLength; i++) {
x = param_array[i].toString().split('=');
params[x[0]] = x[1];
}
return params;
}
return {};
}
A much simpler way to do this would be:
let url = new URL(window.location.href)
url.searchParams.delete('state');
window.location.search = url.search;
You can read about URLSearchParams.delete() in the MDN Web Docs.
Sorry if this is wrong just as i think &state=1,2,3,4,5,6 is absolute its just depends on number to pick states just like my web
var url = '?folder=app&test=true&state=1';
url = url.substring(0, url.indexOf('&s'));
$('#demo').text(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='demo'></span>
var url = '?folder=app&test=true&state=1';
url = url.split('&folder=');
console.log(url);
Here is the URL :
www.example.com/?param%5B%5D=A¶m%5B%5D=B
the %5B%5D part is [] to pass param as an array, which is encoded in url.
Now, I want to remove one of parameters , desired output is:
www.example.com/?param%5B%5D=B
I have searched for this but found nothing!
All the answers are about removing a single value parameter, not multiple.
UPDATE:
I don't know the exact position of the parameter, i.e the URL could be something like this:
www.example.com/?test=124&test2=456¶m%5B%5D=A¶m%5B%5D=B
You can take advantage of URL WebAPI.
https://developer.mozilla.org/en-US/docs/Web/API/URL
var base = 'http://www.example.com/'
var query = '?param%5B%5D=A¶m%5B%5D=B';
var url = new URL(base + query);
var params = new URLSearchParams(url.search);
var filteredParams = params.getAll('param[]')
.filter(function(el) {
return el !== "A";
}).map(function(el){
return ['param[]', el];
});
var newParams = new URLSearchParams(filteredParams);
var url = new URL(base + '?' + newParams.toString() );
console.log(url.toString());
Here is an example on how to extract the params from the URL.
Now how to use them on a user user interaction form (UI) is up to you.
// Use this to get the document location:
var ActualURL = document.location.href;
console.log("This snippet URL: "+ActualURL);
// Only for this demo, I "simulate" a URL.
// ActualURL is overwritten here.
var ActualURL = "www.example.com/?param%5B%5D=A¶m%5B%5D=B";
console.log("FAKED URL: "+ActualURL);
var domain = ActualURL.split("?")[0];
console.log("Domain: "+domain);
var params = ActualURL.split("?")[1];
var param_array = params.split("&");
for (i=0;i<param_array.length;i++){
console.log( "Param #"+i+": "+param_array[i] );
}
console.log("Rebuilted URL with only param #2: "+domain+"?"+param_array[1]);
For example, I have this URL:
http://www.shafadoc.ir/#!mykey=ali
how can get the value of mykey?
If you only have one parameter you can do that:
var param = location.search.split('mykey=')[1]
EDIT:
This is probably better:
var param = window.location.hash.substr(1);
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 1 year ago.
How to get "GET" variables from request in JavaScript?
Does jQuery or YUI! have this feature built-in?
Update June 2021:
Today's browsers have built-in APIs for working with URLs (URL) and query strings (URLSearchParams) and these should be preferred, unless you need to support some old browsers or Opera mini (Browser support).
Original:
All data is available under
window.location.search
you have to parse the string, eg.
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
just call the function with GET variable name as parameter, eg.
get('foo');
this function will return the variables value or undefined if variable has no value or doesn't exist
You could use jquery.url I did like this:
var xyz = jQuery.url.param("param_in_url");
Check the source code
Updated Source: https://github.com/allmarkedup/jQuery-URL-Parser
try the below code, it will help you get the GET parameters from url .
for more details.
var url_string = window.location.href; // www.test.com?filename=test
var url = new URL(url_string);
var paramValue = url.searchParams.get("filename");
alert(paramValue)
Just to put my two cents in, if you wanted an object containing all the requests
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
var QueryString = getRequests();
//if url === "index.html?test1=t1&test2=t2&test3=t3"
console.log(QueryString["test1"]); //logs t1
console.log(QueryString["test2"]); //logs t2
console.log(QueryString["test3"]); //logs t3
Note, the key for each get param is set to lower case. So, I made a helper function. So now it's case-insensitive.
function Request(name){
return QueryString[name.toLowerCase()];
}
Unlike other answers, the UrlSearchParams object can avoid using Regexes or other string manipulation and is available is most modern browsers:
var queryString = location.search
let params = new URLSearchParams(queryString)
// example of retrieving 'id' parameter
let id = parseInt(params.get("id"))
console.log(id)
You can use the URL to acquire the GET variables. In particular, window.location.search gives everything after (and including) the '?'. You can read more about window.location here.
A map-reduce solution:
var urlParams = location.search.split(/[?&]/).slice(1).map(function(paramPair) {
return paramPair.split(/=(.+)?/).slice(0, 2);
}).reduce(function (obj, pairArray) {
obj[pairArray[0]] = pairArray[1];
return obj;
}, {});
Usage:
For url: http://example.com?one=1&two=2
console.log(urlParams.one) // 1
console.log(urlParams.two) // 2
Today I needed to get the page's request parameters into a associative array so I put together the following, with a little help from my friends. It also handles parameters without an = as true.
With an example:
// URL: http://www.example.com/test.php?abc=123&def&xyz=&something%20else
var _GET = (function() {
var _get = {};
var re = /[?&]([^=&]+)(=?)([^&]*)/g;
while (m = re.exec(location.search))
_get[decodeURIComponent(m[1])] = (m[2] == '=' ? decodeURIComponent(m[3]) : true);
return _get;
})();
console.log(_GET);
> Object {abc: "123", def: true, xyz: "", something else: true}
console.log(_GET['something else']);
> true
console.log(_GET.abc);
> 123
You can parse the URL of the current page to obtain the GET parameters. The URL can be found by using location.href.
If you already use jquery there is a jquery plugin that handles this:
http://plugins.jquery.com/project/query-object
The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.
function getUrlParameter(name) {
var urlOld = window.location.href.split('?');
urlOld[1] = urlOld[1] || '';
var urlBase = urlOld[0];
var urlQuery = urlOld[1].split('#');
urlQuery[1] = urlQuery[1] || '';
var parametersString = urlQuery[0].split('&');
if (parametersString.length === 1 && parametersString[0] === '') {
parametersString = [];
}
// console.log(parametersString);
var anchor = urlQuery[1] || '';
var urlParameters = {};
jQuery.each(parametersString, function (idx, parameterString) {
paramName = parameterString.split('=')[0];
paramValue = parameterString.split('=')[1];
urlParameters[paramName] = paramValue;
});
return urlParameters[name];
}
Works for me in
url: http://localhost:8080/#/?access_token=111
function get(name){
const parts = window.location.href.split('?');
if (parts.length > 1) {
name = encodeURIComponent(name);
const params = parts[1].split('&');
const found = params.filter(el => (el.split('=')[0] === name) && el);
if (found.length) return decodeURIComponent(found[0].split('=')[1]);
}
}