Vanilla | Append UTM parameters to links by class name

//Append url parameters to links with classname
(function() {
var domainsToDecorate = ['domain.com'], queryParams = ['utm_medium','utm_source','utm_campaign','utm_term','utm_content'];
var links = document.querySelectorAll('.rewrite-url'); 
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
 for (var domainIndex = 0; domainIndex < domainsToDecorate.length; domainIndex++) { 
   if (links[linkIndex].href.indexOf(domainsToDecorate[domainIndex]) > -1 && links[linkIndex].href.indexOf("#") === -1) {
     links[linkIndex].href = decorateUrl(links[linkIndex].href);
   }
 }
}
function decorateUrl(urlToDecorate) {
 urlToDecorate = (urlToDecorate.indexOf('?') === -1) ? urlToDecorate + '?' : urlToDecorate + '&';
 var collectedQueryParams = [];
 for (var queryIndex = 0; queryIndex < queryParams.length; queryIndex++) {
   if (getQueryParam(queryParams[queryIndex])) {
     collectedQueryParams.push(queryParams[queryIndex] + '=' + getQueryParam(queryParams[queryIndex]))
   }
 }
 return urlToDecorate + collectedQueryParams.join('&');
}
function getQueryParam(name) {
 if (name = (new RegExp('[?&]' + encodeURIComponent(name) + '=([^&]*)')).exec(window.location.search))
   return decodeURIComponent(name[1]);
}
My website may contain fan art inspired by existing characters from movies or tv shows, I dont own any rights. Any copyright owner willing to remove those fan arts can contact me here. This is a personal portfolio, the sole use of cookies are for analysing my traffic through Google Analytics, if you're ok with that please accept this terms by closing this disclaimer.