Skip to content

Instantly share code, notes, and snippets.

@harrisonde
Last active April 29, 2017 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harrisonde/db2171810ce69f08cc24455f04b4a3a4 to your computer and use it in GitHub Desktop.
Save harrisonde/db2171810ce69f08cc24455f04b4a3a4 to your computer and use it in GitHub Desktop.
Append query to anchor
/**
* forward-query-strings.js
*
* Harrison DeStefano
* A utility to append query strings to a href value.
* December 05, 2016
*/
'use strict'
var FowardQueryStrings = function(options) {
this.defaults = {
matchHref: options.matchHref || false,
hrefValue: options.hrefValue || null
},
this.store = {
querystring: null
}
};
/*
* Validate URI for query and add value to FQS store.
*/
FowardQueryStrings.prototype.retrieve = function(){
var query = window.location.href.indexOf('?');
if(query >= 0){
this.store.querystring = window.location.href.substring(query);
}
};
/*
* Inject the query string into href values as defined.
*/
FowardQueryStrings.prototype.inject = function(){
if(!this.store.querystring){
return;
}
var anchors = document.querySelectorAll('a');
for(var a in anchors){
if(anchors[a].href){
var anchorURI = getBaseURI(anchors[a].href);
var defaultURI = getBaseURI(this.defaults.hrefValue);
if(this.defaults.matchHref && defaultURI === anchorURI || this.defaults.matchHref === false){
anchors[a].href = anchors[a].href + this.store.querystring;
}
}
}
/*
* Find the base URI
* @param uri (string) The URI to strip to base
* @return uri (string) The base URI or a null reference
*/
function getBaseURI(uri){
var regex = new RegExp('^.+?[^\/:](?=[?\/]|$)');
var base = regex.exec(uri);
return base ? base[0] : null;
}
};
window.addEventListener('load', function(){
var options = { matchHref: true, hrefValue: 'https://donate.weizmann-usa.org' };
var fqs = new FowardQueryStrings(options);
fqs.retrieve();
fqs.inject();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment