3 Ways to Build Query Strings In Javascript (Simple Examples)

Welcome to a quick tutorial and examples on how to build a query string in Javascript. So you want to send data from one place to another and need to create a URL string with parameters?

An easy way to build a query string in Javascript is to use a URLSearchParams object:

  • var query = new URLSearchParams();
  • query.append("KEY", "VALUE");
  • var url = "http://site.com/page?" + query.toString();

That covers the basics, but there are more methods that we can use – Read on for more!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Query Strings Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

BUILDING QUERY STRINGS

All right, let us now get into the various ways and examples of how to create a query string in Javascript.

 

METHOD 1) URL PARAMS OBJECT

1-URLSearchParams.html
<script>
// (A) URL SEARCH PARAMS OBJECT TO QUICKLY BUILD QUERY STRING
var query = new URLSearchParams({
  name : "John Doe", 
  email : "john@doe.com",
  colors : JSON.stringify(["Red", "Green", "Blue"])
});
query.append("KEY", "VALUE"); // To append more data
 
// (B) CONVERT TO STRING, APPEND TO URL
var url = "http://site.com/page?" + query.toString();
console.log(url);
 
// (C) WHATEVER COMES NEXT...
// REDIRECT OR AJAX CALL OR FETCH
// window.location.href = url;
</script>

As in the introduction above, this is one of the easiest ways to build a query string in modern-day Javascript – Just create a new URLSearchParams() object, append data, and convert it toString() – Done.

 

 

METHOD 2) USING URI.JS LIBRARY

2-uri-js.html
<!-- CHECK https://cdnjs.com/libraries/URI.js FOR LATEST VERSION -->
<!-- DOCS: https://medialize.github.io/URI.js/ -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.19.7/URI.min.js"></script>
<script>
// (A) TARGET URL
var uri = new URI("http://site.com/page");
 
// (B) SET PARAMETERS
uri.setSearch({
  name : "John Doe",
  email : "john@doe.com",
  colors : JSON.stringify(["Red", "Green", "Blue"])
});
uri.addSearch("KEY", "VALUE"); // To append more data
 
// (C) OUTPUT ENTIRE URL STRING
var url = uri.toString();
console.log(url);
 
// (D) WHATEVER COMES NEXT...
// REDIRECT OR AJAX CALL OR FETCH
// window.location.href = url;
</script>

Now, URLSearchParams is well supported in most modern browsers. But when you have to work with the ancient browsers, this is a possible alternative – Use a library called URI.JS. The syntax is pretty much the same and should be straightforward enough. Check out the official URI.js documentation if you want to learn more about this library.

 

 

METHOD 3) MANUAL QUERY STRING

3-manual.html
<script>
// (A) TARGET URL
var url = encodeURI("http://site.com/my page");
 
// (B) APPEND DATA TO QUERY STRING
// TAKE NOTE OF ? FOR FIRST PARAMETER, & FOR SECOND PARAMETER AND BEYOND
url += "?name=" + encodeURIComponent("John Doe");
url += "&email=" + encodeURIComponent("john@doe.com");
url += "&KEY=" + encodeURIComponent("VALUE");
 
// (C) TO APPEND AN ARRAY - JSON ENCODE
// ON SERVER SIDE, JSON DECODE COLORS
var colors = ["Red", "Green", "Blue"];
url += "&colors=" + JSON.stringify(colors);
 
// (D) FULL URL
// http://site.com/my%20page?name=John%20Doe&email=john%40doe.com&KEY=VALUE&colors=["Red","Green","Blue"]
console.log(url);
 
// (E) WHATEVER COMES NEXT...
// REDIRECT OR AJAX CALL OR FETCH
// window.location.href = url;
</script>

When all else fails, this is the traditional way to create a query string – Manually. Just take a moment to understand the syntax:

  • Query strings are appended to the end of the URL – http://site.com/page?KEY=VALUE&KEY=VALUE...
  • Take note of the use of encodeURI() and encodeURIComponent() here.
    • Some characters such as empty spaces and @ are not allowed in the URL. These functions will convert these “illegal characters” to their respective code.
    • The rather confusing part is that we have to use encodeURI() for the http://site.com/path/ part, and encodeURIComponenet() for the parameters.
    • Basically, some history here – The URL and parameter both accept rather different character sets… Just take note, to use different encode functions for each segment.

 

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

USEFUL FUNCTIONS & OBJECTS TO KNOW

Function/Object Description Reference Link
encodeURI() Encode the URL. Click Here
encodeURIComponent() Encode a single URI component. Click Here
new URLSearchParams() URL parameters object. Click Here

 

INFOGRAPHIC CHEATSHEET

Ways to Build Query String In Javascript (Click To Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published.