Adding a Parameter to the Url with JavaScript

Adding a parameter to the URL with JavaScript

A basic implementation which you'll need to adapt would look something like this:

function insertParam(key, value) {
key = encodeURIComponent(key);
value = encodeURIComponent(value);

// kvp looks like ['key1=value1', 'key2=value2', ...]
var kvp = document.location.search.substr(1).split('&');
let i=0;

for(; i<kvp.length; i++){
if (kvp[i].startsWith(key + '=')) {
let pair = kvp[i].split('=');
pair[1] = value;
kvp[i] = pair.join('=');
break;
}
}

if(i >= kvp.length){
kvp[kvp.length] = [key,value].join('=');
}

// can return this or...
let params = kvp.join('&');

// reload page with new params
document.location.search = params;
}

This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match


the slow regex method I benchmarked against for completions sake (approx +150% slower)

function insertParam2(key,value)
{
key = encodeURIComponent(key); value = encodeURIComponent(value);

var s = document.location.search;
var kvp = key+"="+value;

var r = new RegExp("(&|\\?)"+key+"=[^\&]*");

s = s.replace(r,"$1"+kvp);

if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};

//again, do what you will here
document.location.search = s;
}

How can I add or update a query string parameter?

I wrote the following function which accomplishes what I want to achieve:

function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
}

Add parameters to url using JavaScript

getElementsByClassName returns an array and so you need to either loop over all elements or if you are sure to only having one element, you can select the first element with [0] after image.

If you want to apply it to all images, you can loop over them. In the following example I'm using querySelectorAll to select the class .parameter.

const viewportWidth = '100px';

const viewportHeight = '100px';

const dpr = 2;

const images = document.querySelectorAll(".parameter");

images.forEach( ( image ) => {

const imageSrc = image.getAttribute("src");

image.setAttribute("src", imageSrc + "?w=" + viewportWidth + "&h=" + viewportHeight + "&dpr=" + dpr + "&fit=crop");

} );
<img class="parameter" src="http://url-to-image.com/image.jpg" style="width: 100%">


Related Topics



Leave a reply



Submit