How to Append a Query Parameter to an Existing Url

How can I append a query parameter to an existing URL?

This can be done by using the java.net.URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax.

The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.

public class StackOverflow26177749 {

public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
URI oldUri = new URI(uri);

String newQuery = oldUri.getQuery();
if (newQuery == null) {
newQuery = appendQuery;
} else {
newQuery += "&" + appendQuery;
}

return new URI(oldUri.getScheme(), oldUri.getAuthority(),
oldUri.getPath(), newQuery, oldUri.getFragment());
}

public static void main(String[] args) throws Exception {
System.out.println(appendUri("http://example.com", "name=John"));
System.out.println(appendUri("http://example.com#fragment", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe@email.com", "name=John"));
System.out.println(appendUri("http://example.com?email=john.doe@email.com#fragment", "name=John"));
}
}

Shorter alternative

public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
URI oldUri = new URI(uri);
return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(),
oldUri.getQuery() == null ? appendQuery : oldUri.getQuery() + "&" + appendQuery, oldUri.getFragment());
}

Output

http://example.com?name=John
http://example.com?name=John#fragment
http://example.com?email=john.doe@email.com&name=John
http://example.com?email=john.doe@email.com&name=John#fragment

How to append query string variable to existing URL with history.pushState?

Here you go boss, parse the current URL query string, make a variable, then add it into the equation. It is dynamic as you wanted for its contents are based upon the click.

$(document).ready(function() { 
$(".photo-block").on("click", ".photo", function(){
function query_string(variable){
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){
return pair[1];
}}return(false);}
history.pushState({}, '','?info=' + info +'?photo='+$(this).attr("id"));
$(".photo-viewer").show();
});
});

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;
}
}

I want to append the query string on a URL to all anchor links on the page

How about using querySelectorAll in vanilla javascript instead of jquery. Also, kill your leading '?' in querystring. And if part of your question involves how to get the querystring from the current page's url, use window.location.search.

In the snippet below, you have some google search anchors. One searches 'x', and the other searches 'y'. Your query string further specifies that in both anchors, you want a safe search for images.

// You will use window.location.searchlet querystring = '?tbm=isch&safe=active' 
if(querystring.startsWith('?')) querystring = querystring.replace('?', '');
for(let a of document.querySelectorAll('a')) { a.href += (a.href.match(/\?/) ? '&' : '?') + querystring;}
<a href='https://www.google.com/search?q=x'>search x images safely</a><br/><a href='https://www.google.com/search?q=y'>search y images safely</a>

Angular: append query parameters to URL

This could be archived by using the Router class:

Using a component:

import { Router, ActivatedRoute } from '@angular/router';

@Component({})
export class FooComponent {
constructor(
private _route: ActivatedRoute,
private _router: Router
){}

navigateToFoo(){
// changes the route without moving from the current view or
// triggering a navigation event,
this._router.navigate([], {
relativeTo: this._route,
queryParams: {
newOrdNum: '123'
},
queryParamsHandling: 'merge',
// preserve the existing query params in the route
skipLocationChange: true
// do not trigger navigation
});
}
}

For more info check this book and the angular Router API



Related Topics



Leave a reply



Submit