2
\$\begingroup\$

I have written this code which adds a querystring to a URL:

exports.addQueryString = function(url, queryString) {
 var isQuestionMarkPresent = url && url.indexOf('?') !== -1,
 separator = '';
 if (queryString) {
 separator = isQuestionMarkPresent ? '&' : '?';
 url += separator + queryString;
 }
 return url;
};

Is there any way I can write this better?

Usage:

addQueryString('http://example.com', 'q=1&val=3&user=me');
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Dec 10, 2013 at 6:15
\$\endgroup\$
2
  • \$\begingroup\$ Have you considered proper encoding of query string values? From your code it looks like it might be a separate operation since you already pass in a full query string but may be relevant overall. \$\endgroup\$ Commented Jan 9, 2014 at 14:27
  • \$\begingroup\$ @PeterMonks Yes..That is indeed a great point but I handled this case later (after I posted the question here). Once again thanks. \$\endgroup\$ Commented Jan 9, 2014 at 14:48

2 Answers 2

4
\$\begingroup\$

I think that is ok, only that i see not necesary make url.indexOf('?') if queryString is empty, because you are not going to use it.

exports.addQueryString = function(url, queryString) { 
 if (queryString) {
 var isQuestionMarkPresent = url && url.indexOf('?') !== -1,
 separator = isQuestionMarkPresent ? '&' : '?';
 url += separator + queryString;
 }
 return url;
};
answered Jan 9, 2014 at 10:28
\$\endgroup\$
1
\$\begingroup\$

What happens when you just want to add a single queryString to and already long queryString? You would need to know the entire queryString to do that, just to add a single new value.

What your function should do is take a single queryString value and if it already exists it should update it and if it doesn't exist it should append it.

answered Dec 10, 2013 at 8:27
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.