rockstardev
rockstardev

Reputation: 13547

Add parameter to URL which may or may not have query parameters?

I have a URL that could be any of the following (or more):

http://www.mysite.com/some/url
http://www.mysite.com/some/url?a=b
http://www.mysite.com/some/url?a=b&c=d

I want an easy way to append a another value to the end, for example "e=f. So that in each case I would end up with:

http://www.mysite.com/some/url?e=f
http://www.mysite.com/some/url?a=b&e=f
http://www.mysite.com/some/url?a=b&c=d&e=f

What is the easiest way to do this. The following will not work for all cases:

var url = 'http://www.mysite.com/some/url';
var newQuery = 'e=f';
url += '?' + newQuery;

Is there something built into Jquery that could handle parsing URLs and adding parameters?

Upvotes: 1

Views: 84

Answers (4)

putvande
putvande

Reputation: 15213

You could do :

var url = 'http://www.mysite.com/some/url';
var newQuery = 'e=f';
url += (url.indexOf('?') == -1 ? '?' : ' &') + newQuery;

This will check with indexOf if ? isn't in the URL and add the ? otherwise the & + your newQuery.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

Upvotes: 1

Aditya Shedge
Aditya Shedge

Reputation: 31

take your additional parameters in an array variable with string elements and add these variables to ur url

dynamically update array and add parameters

example:

var additional_params = ['e=f', 's=e']

if additional_params.length != 0

"http://www.mysite.com/some/url?" + additional_params.join('&')

Upvotes: 0

Venkata Krishna
Venkata Krishna

Reputation: 15122

This will add a query string if you don't have it (or) appends to the existing one if you have one already.

var url = 'http://www.mysite.com/some/url?a=b';
var newQuery = 'e=f';
url += ((url.indexOf('?') != -1) ? '&' : '?') + newQuery;

Upvotes: 2

Ziarno
Ziarno

Reputation: 7572

Have newQueries always be an array, if it's empty - just use the url, if not - append the values.

var url = 'http://www.mysite.com/some/url';
var newQueries = ['e=f', 's=e', 'x=y'];
url += newQueries.length && '?' + newQueries.join('&');

Upvotes: 0

Related Questions