How can I use one javascript object on many pages? - javascript

I want to add properties to an object and pass that object to another page.

A few things:
I would combine the functions in a namespace;
you don't need Base64 encoding, since encodeURIComponent() will suffice;
This is not suitable for large objects, you would need localStorage for that;
Your code had a few gotchas, such as when an href already contains a ?;
I've reworked it like so:
DataTransferService = {
sendToUrl: function(obj, url, name) {
var value = JSON.stringify(obj);
name = name || 'data';
return url + (url.indexOf('?') === -1 ? '?' : '&') + name + '=' + encodeURIComponent(value);
},
receiveFromCurrentUrl: function(name) {
return receiveFromUrl(window.location.href, name);
},
receiveFromUrl: function(url, name) {
var value;
name = name || 'data';
url = url || window.location.href;
if ((value = this.getUrlParameter(name, url)) !== null) {
return JSON.parse(value);
}
},
getUrlParameter:function(name, url) {
var p, qs;
if ((p = url.indexOf('?')) === -1) {
return null;
}
qs = url.substr(p + 1).split('&');
for (var i = 0, len = qs.length; i != len; ++i) {
var pair = qs[i].split('=');
if (pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
return null;
}
};
To use:
var obj = {
a: 123,
b: 456,
c: [1, 3, 5]
};
var url = DataTransferService.sendToUrl(obj, '/path/to/page');
// "/path/to/page?data=..."
location = url;
On the receiving page:
var obj = DataTransferService.receiveFromCurrentUrl();
// work with obj here

Functions to put in your global js file..
function GotoPage(relUrl) {
var json = JSON.stringify({param1:val1, param2:val2});
window.location.href = relUrl.concat('?data=').concat(Base64.encode(json));
}
function GetUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Assume we're navigating from page1 to page2.. in page2's .js file you'll write:
var base64data = GetUrlVars()['data']
var jsondata = Base64.decode(base64data)
var data = JSON.parse(data);
var param1 = data.param1;
//do something with the objects properties
For the Base64 implementation see: How can you encode a string to Base64 in JavaScript?

Related

How to remove some parameters from an URL string?

I have this var storing a string that represents a URL full of parameters. I'm using AngularJS, and I'm not sure if there is any useful module (or maybe with plain JavaScript) to remove the unneeded URL parameters without having to use regex?
For example I need to remove &month=05 and also &year=2017 from:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
Use the URLSearchParams API:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
var urlParts = url.split('?');
var params = new URLSearchParams(urlParts[1]);
params.delete('month');
params.delete('year')
var newUrl = urlParts[0] + '?' + params.toString()
console.log(newUrl);
The advantage of using this API is that it works with and creates strings with correct percent encoding.
For more information, see MDN Developer Reference - URLSearchParams API.
You can use this function that take 2 parameters: the param you are trying to remove and your source URL:
function removeParam(key, sourceURL) {
var rtn = sourceURL.split("?")[0],
param,
params_arr = [],
queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
if (queryString !== "") {
params_arr = queryString.split("&");
for (var i = params_arr.length - 1; i >= 0; i -= 1) {
param = params_arr[i].split("=")[0];
if (param === key) {
params_arr.splice(i, 1);
}
}
rtn = rtn + "?" + params_arr.join("&");
}
return rtn;
}
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var url2 = removeParam("month", url);
var url3 = removeParam("year", url2);
console.log(url3);
Alternative solution with a regex
Sure you can use RegExr: ((&)year=([^&]))|((&)month=([^&]))
use:
url = url.replace(/(year=([^&]*))|(month=([^&]*))/g, '');
Read more regex :)...
function removeParam(name, url){
return url.replace('/((&)*' + name + '=([^&]*))/g','');
}
var url = "?derivate=21&gear_type__in=13&engine=73&month=05&year=2017"
function removeParam(name, _url){
var reg = new RegExp("((&)*" + name + "=([^&]*))","g");
return _url.replace(reg,'');
}
url = removeParam('year', url);
url = removeParam('month', url);
document.getElementById('url-replace').innerHTML = url;
<div id="url-replace"></div>
Using string replace:
var url = "at merge ?derivate=21&gear_type__in=13&engine=73&month=05&year=2017";
var modifiedUrl = url.replace('&month=05','').replace('&year=2017','');
console.log(modifiedUrl);
You can use the library https://www.npmjs.com/package/query-string
Convert the params to an object and then just use delete params.year delete params.month and convert it back and add it to the original url
const queryString = require('query-string');
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
console.log(location.hash);
//=> '#token=bada55cafe'
const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'
Enhnaced #Mistalis's answer.
Return the value of the last occurrence of a param
Remove the ? of the removed param was the only param
Url encoded the query params to ensure browser stately
function pruneParams(key, url) {
var urlParts = url.split('?');
var rtnUrl = urlParts[0];
var paramParts;
var paramValue;
var params_arr = [];
var queryString = decodeURIComponent(urlParts[1] || '');
if (queryString !== '') {
params_arr = queryString.split('&');
for (var i = params_arr.length - 1; i >= 0; --i) {
paramParts = params_arr[i].split('=');
if (paramParts[0] === key) {
paramValue = paramParts[1];
params_arr.splice(i, 1);
}
}
if (params_arr.length) {
var wasEncoded = url.split('&').length < 2;
rtnUrl = rtnUrl + '?' + (wasEncoded ? encodeURIComponent(params_arr.join('&')) : params_arr.join('&'));
}
}
return { url: rtnUrl, [key]: paramValue, paramCount: params_arr.length > 1 };
}
var u1 = 'http://localhost:4200/member/';
var u2 = 'http://localhost:4200/member/?ts=23423424';
var u3 = 'http://localhost:4200/member/?fooo=2342342asfasf&ts=252523525';
var u4 = 'http://localhost:4200/member?foo=234243&ts=234124124&bar=21kfafjasf&ts=223424234&dd=This Is A Line';
var u5 = 'http://localhost:4200/member?foo%3D234243%26ts%3D2242424%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line';
console.log(pruneParams('ts', u1));
console.log(pruneParams('ts', u2));
console.log(pruneParams('ts', u3));
console.log(pruneParams('ts', u4));
console.log(pruneParams('ts', u5));
// {
// url: 'http://localhost:4200/member/',
// ts: undefined,
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/',
// ts: '23423424',
// paramCount: false,
// }
// {
// url: 'http://localhost:4200/member/?fooo=2342342asfasf',
// ts: '252523525',
// paramCount: false,
// },
// {
// url: 'http://localhost:4200/member?foo=234243&bar=21kfafjasf&dd=This Is A Line',
// ts: '234124124',
// paramCount: true,
// }
// {
// url: 'http://localhost:4200/member?foo%3D234243%26bar%3D21kfafjasf%26dd%3DThis%20Is%20A%20Line',
// ts: '2242424',
// paramCount: true,
// }
Taken from #Mistalis answer but tidied up. Useful if URLSearchParams API is not available.
const removeUrlParam = function (url, param) {
var parts = url.split('?')
url = parts[0]
if (parts.length !== 2) return url
var qs = parts[1]
if (qs === '') return url
var params = qs.split('&')
for (var i = params.length - 1; i >= 0; i -= 1) {
var key = params[i].split('=')[0]
if (key === param) params.splice(i, 1)
}
return params.length ? url + '?' + params.join('&') : url
}
var url1 = removeUrlParam('/xxxxx', 'a')
var url2 = removeUrlParam('/xxxxx?a=1', 'a')
var url3 = removeUrlParam('/xxxxx?a=1&b=2', 'a')
console.log(url1, url2, url3)

How can I put all the URL parameters in array of objects using jQuery?

I have a giving string/url like this
https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables
I need to loop thought each parameter in the url. If the value starts with : this indicated that it is a variable an I will need to change that value dynamically by looking at the corresponding meta attribute that matches that variable.
Here is my code in which loops over an array and sets the value of the parameters.
var baseURL = getBaseURL(url);
var params = getParams(url);
var newParams = $.each(params, function(index, param){
if( param.value.substring(0, 1) == ':'){
var myVar = param.value.substring(1);
param.value = $('meta[name=" + myVar + "']).attr('value');
}
});
var finalURL = baseURL + '?' + jQuery.param( newParams );
function getParams(url){
// This function should return an array of objects. Each object should have 2 properties "value" and "name". The "name" property should be the name of the parameter (ie. var1, var2, var3 .....) and the "value" attribute should contains the value of the parameter (ie. 100, :somevar, :morevariables)
}
function getBaseURL(url){
var cutoff = url.indexOf('?');
if( cutoff > -1){
return url.substring(0, cutoff - 1);
}
return url;
}
I need help converting the parameters of a giving URL to array of object. How can I do this in jQuery?
You dont need jQuery for this one.
function getParams(url) {
var queryString = url.substring(url.indexOf('?') + 1);
var paramsArr = queryString.split('&');
var params = [];
for (var i = 0, len = paramsArr.length; i < len; i++) {
var keyValuePair = paramsArr[i].split('=');
params.push({
name: keyValuePair[0],
value: keyValuePair[1]
});
}
return params;
}
Here is an example using map
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables&test';
function getParamArray(url) {
var queryString = url.substring(url.lastIndexOf("?") + 1);
return queryString.split('&').map(function(sParam) {
var param = sParam.split('=');
return {
name: param[0],
value: decodeURIComponent(param[1])
};
});
}
document.getElementById("output").innerHTML = JSON.stringify(getParamArray(url), null, 2);
<pre id="output"></pre>
With a regular expresion and JSON.parse:
var url = 'https://example.com/loadcontent?var1=100&var2=:somevar&var3=:morevariables';
url = url.replace(/^.*\?/,'');
url = url.replace(/(\w+)=?([\w:]*)/g,'{"name":"$1","value":"$2"}');
url = url.replace(/&/g,',');
var paramsObject = JSON.parse("["+url+"]");
/*
Returns:
Array [{"name":"var1","value":"100"},{"name":"var2","value":":somevar"},{"name":"var3","value":":morevariables"}];
*/
You don't even need JQuery for this.
<script type="text/javascript">
var paramStr = window.location.search;
var params = paramStr.substring(1, paramStr.length).split('&');
var paramList = [];
for (var index=0; index < params.length; index++) {
var param = params[index].split('=');
paramList.push({name: param[0], value: param[1]});
}
</script>
The result:
[Object]0: Object
name: "a"
value: "b"
...
var url=new URLSearchParams(window.location.search);
var params = [];
for(var value of url.keys())
{
params.push({
name: value,
value: url.get(value)
});
}

Prase query string from url javascript

my url look like http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1
now i am looking for a function where i will pass url and query string name then that should return value.
so i did it this way but not working.
function getQueryVariable(url,variable) {
var query = url;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
calling like this way
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert(getQueryVariable(x,'sort'));
alert(getQueryVariable(x,'sortdir'));
alert(getQueryVariable(x,'page'));
where i made the mistake?
EDIT
working code
$.urlParam = function(url,name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1'
alert($.urlParam(x,'sort'));
alert($.urlParam(x,'sortdir'));
alert($.urlParam(x,'page'));
https://jsfiddle.net/z99L3985/1/
thanks
may be the following will help
function getUrlVars(url) {
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var x='http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1';
var queryVars = getUrlVars(x);
alert(queryVars['sort']);
alert(queryVars['sortdir']);
alert(queryVars['page']);
I just get this from somewhere else as well..
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
console.log(vars);
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] === variable){return pair[1];}
}
return(false);
}
so far its doing its job.
with url: "http://urlhere.com/general_journal?from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2"
if im going to get the 'page' variable result would be : `2`
console.log(getQueryVariable('page'));
my query variable is only getting the search.substring(1) part of the the url so basically it only gets from=01%2F14%2F2016&to=01%2F14%2F2016&per_page=25&page=2 part of the url then from that it splits it and then return the value of the string parameter you specified on the function call getQueryVariable('page') for example.
Maybe this helps
var getUrlVars = function(url){
var vars = [], hash;
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(decodeURIComponent(hash[0]));
vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
}
if(vars[0] == url){
vars =[];
}
return vars;
}
Then in your code
var params = getUrlVars("http://localhost:13562/Student/RefreshStudents?sort=FirstName&sortdir=ASC&page=1");
console.log(params["sort"]) // FirstName

having trouble overwriting querystring with history.PushState

I can't figure out how to correctly use push state. I'm getting weird url's like so:
http://website.net/home?http://website.net/home=undefined&tab=browse
And can't seem to get it to work no matter what I try. I need domain/path to stay the same, I just want to rebuild the querystring (which I do in another function) then apply history.pushState()
Here's a basic look at the code, abbreviated to show the problem in question.
var sk = {
//push function
pushState: function(qs,callback){
var i = 0, uri = '';
$.each(qs,function(k,v){
if(k=="" || v==""){
delete qs[k];
}
});
$.each(qs,function(k,v){
if(i == 0){
uri +='?';
}else{
uri +='&';
}
uri +=k+'='+encodeURIComponent(v);
i++;
});
var obj ={ Title: $('title').html(), Url: uri }
if(typeof callback !== "undefined" && callback !== false){
obj[callback[0]] = callback[1];
}
history.pushState(obj,obj.Title,obj.Url);
},
//parse current url and return querystring
getQSvars : function(){
var vars = {}, hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars[hash[0]] = hash[1];
}
return vars;
},
};

How can I get query string parameter in Javascript or jQuery?

I have a link like this:
http://localhost:8162/UI/Link2.aspx?txt_temp=123abc
I want to get the value 123abc . I have followed this How can I get query string values in JavaScript? and
jquery get querystring from URL
$(document).ready(function () {
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
onload = function () {
alert(getParameterByName('txt_temp'));
alert(getUrlVars()["txt_temp"]);
}
});
But it does not work.
Suppose you have URL with many params eg:-
"http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
Then in js you can do like:
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
OR
var url = window.location.href
then split main url like:
hashes = url.split("?")[1]
//hashes holds this output "txt_temp=123abc&a=1&b=2"
Then again you can split by & to get individual param
EDIT
Check this example:
function getUrlVars() {
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2";
var vars = {};
var hashes = url.split("?")[1];
var hash = hashes.split('&');
for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
vars[params[0]] = params[1];
}
return vars;
}
Output
getUrlVars()
Object {txt_temp: "123abc", a: "1", b: "2"}
It doesn't work because you're running the functions inside of onload, which doesn't fire inside of document.ready, because by the time the code inside of document.ready executes, onload has already fired. Just get your code out of the onload event:
http://jsfiddle.net/whp9hnsk/1/
$(document).ready(function() {
// Remove this, this is only for testing.
history.pushState(null, null, '/UI/Link2.aspx?txt_temp=123abc');
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// You may also place this inside of a function,
// and execute it when you desire, but `onload` is not going
// to fire by itself, when inside of document.ready
alert(getParameterByName('txt_temp'));
alert(getUrlVars()["txt_temp"]);
});
This should get you started:
function parseQueryStr( str, obj ) {
// Return object
obj = obj || {};
// Looping through our key/values
var keyvalues = str.split('&');
for( var i=0; i<keyvalues.length; i++ ) {
// Break apart our key/value
var sides = keyvalues[i].split( '=' );
// Valid propery name
if( sides[0] != '' ) {
// Decoding our components
sides[0] = decodeURIComponent( sides[0] );
sides[1] = decodeURIComponent( sides.splice( 1, sides.length-1 ).join( '=' ) );
// If we have an array to deal with
if( sides[0].substring( sides[0].length - 2 ) == '[]' ) {
var arrayName = sides[0].substring( 0, sides[0].length - 2 );
obj[ arrayName ] = obj[ arrayName ] || [];
obj[ arrayName ].push( sides[1] );
}
// Single property (will overwrite)
else {
obj[ sides[0] ] = sides[1];
}
}
}
// Returning the query object
return obj;
}
var href = window.location.href.split('#');
var query = href[0].split('?');
query.splice(0,1);
var get = parseQueryStr(query.join('?'));
alert( get.txt_temp );
You can use:
var param = new URLSearchParams(urlString).get('theParamName');
Or if searching the current page:
var param = new URLSearchParams(location.search).get('theParamName');
you have to slice the everything before and after "=" so first answer is a bit incomplete. Here is the answer which works for querystrings includes "=" in it too :) Like:
https://localhost:5071/login?returnUrl=/writer/user?id=315&name=john
Thanks to user abhi
var getUrlVars = function () {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]); //to get name before =
vars[hash[0]] = hashes[i].slice(hashes[i].indexOf('=') + 1); //to take everything after first =
}
return vars;
}
and then get it with
var url = window.getUrlVars()["returnUrl"];
so it will extract "/writer/user?id=315" with "=" too :)
I wrote this one liner with ES6 syntax which follows the method of the accepted answer.
function getParam(key){
return window.location.href.split('?')[1].split('&').filter(x=>x.split('=')[0]==key)[0].split('=')[1];
}
Use:
Lets say the current URL is: https://stackoverflow.com?question=30271461
getParams('question') //30271461

Categories

Resources