encodeURIComponent will work. (You may or may not want the leading ‘?’, depending on what the script is expecting.)

var c= 'd e'
var query= '?a=b&c='+encodeURIComponent(c);
var uri= 'http://www.example.com/script?query='+encodeURIComponent(query);
window.location= uri;

Takes me to:

http://www.example.com/script?query=%3Fa%3Db%26c%3Dd%2520e

When you hover over that it may appear once-decoded in the browser's status bar, but you will end up in the right place.

escape/unescape() is the wrong thing for encoding query parameters, it gets Unicode characters and pluses wrong. There is almost never a case where escape() is what you really need.

Answer from bobince on Stack Overflow
🌐
W3docs
w3docs.com › javascript
How to Encode JavaScript Object to Query-String | W3Docs
The new ES6 format encodes objects to query string in the following way: Javascript encodes a Uniform Resource Identifier (URI) component
Discussions

Query-string encoding of a JavaScript object - Stack Overflow
Is there a fast and simple way to encode a JavaScript object into a string that I can pass via a GET request? No jQuery, no other frameworks—just plain JavaScript :) More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to encode URL parameters? - Stack Overflow
I am trying to pass parameters to a URL which looks like this: http://www.foobar.com/foo?imageurl= And I want to pass the parameters such as an image URL which is generated itself by another API, ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - If I am encoding a URI which will be used as a query string parameter: encodeURI or encodeURIComponent - Stack Overflow
If you want to encode a query string, use encodeURIComponent. More on stackoverflow.com
🌐 stackoverflow.com
How do I put a JSON object in a URL as a GET parameter?

JSON itself is a string. To turn your object into JSON you simply need to call a JSON.stringify(obj). Make sure you url-encode the string as well with encodeURI() before appending it to a link

More on reddit.com
🌐 r/javascript
25
13
December 25, 2017
🌐
Mastering JS
masteringjs.io › tutorials › fundamentals › encodeuricomponent
The encodeURIComponent() Function in JavaScript - Mastering JS
The encodeURIComponent() function in JavaScript allows you to encode special characters in your query string that would otherwise change the meaning of your query string.
🌐
Node.js
nodejs.org › api › querystring.html
Query string | Node.js v26.5.0 Documentation
For example, the query string ... and will not work. By default, percent-encoded characters within the query string will be assumed to use UTF-8 encoding....
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-encode-a-javascript-object-into-a-query-string-ab56554107cb
How to Encode a Javascript Object into a Query String? | by John Au-Yeung | JavaScript in Plain English
January 8, 2022 - Then we call toString to return the query string. ... The property names are used as keys and the property values are used as the values. We can also loop through the object and insert the query parameters with the append method: ... New JavaScript and Web Development content every day.
🌐
GeeksforGeeks
geeksforgeeks.org › node-js-querystring-encode-function
Node.js querystring.encode() Function | GeeksforGeeks
March 8, 2021 - The method iterates through the object’s own properties to generate the query string. It can serialize a single or an array of strings, numbers, and boolean. Any other types of values are coerced to empty strings. During serializing, the UTF-8 encoding format is used to encode any character that requires percent-encoding.
🌐
Attacomsian
attacomsian.com › blog › javascript-encode-url
How to encode a URL using JavaScript
October 13, 2022 - const url = 'http://example.com/!learn ... // output: http://example.com/!learn javascript$/ Ideally, you should use the encodeURIComponent() method only for encoding query string parameters or path segments....
Find elsewhere
🌐
Medium
medium.com › theleanprogrammer › javascript-encode-url-query-parameter-5cd11aeee4b6
Javascript | Encode URL Query Parameter | by Sonika | @Walmart | Frontend Developer | 11 Years | TheLeanProgrammer | Medium
August 25, 2024 - This means that we need to encode these characters when passing them into a URL. Special characters such as &, space, ! when entered in a URL need to be escaped, otherwise, it may cause unpredictable situations. My Use case: Need to accept query string parameters in order to make GET requests.
🌐
TutorialsPoint
tutorialspoint.com › article › query-string-encoding-of-a-javascript-object
Query-string encoding of a Javascript Object - TutorialsPoint
let obj = { name: 'John & Jane', email: 'user@example.com', message: 'Hello World!' }; let qs = Object.keys(obj) .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`) .join('&'); console.log(qs); name=John & Jane&email=user@example.com&message=Hello World! Both approaches effectively convert JavaScript objects to query strings.
🌐
URL Encoder
urlencoder.io › javascript
URL Encoding a String in Javascript | URLEncoder
var baseUrl = 'https://www.google.com/search?q=' var query = 'Hellö Wörld@Javascript' // encode only the query string var completeUrl = baseUrl + encodeURIComponent(query) console.log(completeUrl) // https://www.google.com/search?q=Hellö Wörld@Javascript
🌐
Bitovi
bitovi.com › blog › javascript-query-string-encoding-and-decoding
Can’d Goodies: JavaScript Query String Encoding and Decoding
March 31, 2017 - To encode the location correctly (which could have spaces or special characters), we use can-param before making the fetch request. The fetch API is great, although it doesn’t provide any serialization for your parameters, making can-param ...
🌐
xjavascript
xjavascript.com › blog › query-string-encoding-of-a-javascript-object
How to Encode a JavaScript Object into a Query String Fast and Simple (No jQuery, Plain JavaScript) — xjavascript.com
For most use cases, the URLSearchParams API (built into modern browsers) is the best solution. It automatically handles encoding, key-value pairing, and edge cases like duplicate keys. URLSearchParams accepts an object (or array of [key, value] pairs) and converts it to a query string via toString().
🌐
TutorialsPoint
tutorialspoint.com › query-string-encoding-of-a-javascript-object
Query-string encoding of a Javascript Object
November 27, 2019 - let obj = { name: 'John & Jane', email: 'user@example.com', message: 'Hello World!' }; let qs = Object.keys(obj) .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`) .join('&'); console.log(qs); name=John & Jane&email=user@example.com&message=Hello World! Both approaches effectively convert JavaScript objects to query strings.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-url-encode-example-how-to-use-encodeuricomponent-and-encodeuri
JavaScript URL Encode Example – How to Use encodeURIcomponent() and encodeURI()
August 4, 2020 - encodeURI("http://www.mysite.com/a file with spaces.html") //http://www.mysite.com/a file with spaces.html · When building a URL from query string parameters.
🌐
Medium
garrett-bodley.medium.com › encoding-data-inside-of-a-url-query-string-f286b7e20465
Encoding Data inside of a URL Query String | by Garrett Bodley | Medium
June 8, 2021 - After some brainstorming, I decided to encode the vamp data inside the share link itself as a query string. This would allow me to avoid dealing with complicated permissions on the server, especially when I wanted users to be able to load the shared vamp without making an account on the site. My first idea was to simply take the data structure I was already creating to save vamps to the server, convert it to JSON, and then convert that string to hexadecimal. The Javascript documentation for parseInt() says it can convert strings into hexadecimal and toString() readily converts any hexadecimal back into a string.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-encode-and-decode-a-url-in-javascript
How to Encode and Decode a URL in JavaScript? | GeeksforGeeks
September 2, 2024 - To encode a URL, we can use the querystring.stringify() function to create a query string from an object and then use encodeURIComponent() to encode the resulting string.
Top answer
1 of 3
41

If you want to encode a query string, use encodeURIComponent. The reason is simple: among a few other chars, it'll encode the forward slash and amersand that encodeURI will not.

encodeURIComponent

What's the use? Say you want to encode a URL and pass it in the query string, this will let you encode all the characters so you get something like this:

encodeURIComponent('http://abc.com/my page.html?name=bob&foo=bar')

to get the result

"http%3A%2F%2Fabc.com%2Fmy%20page.html%3Fname%3Dbob%26foo%3Dbar"

You can now safely pass that as a query string like so:

http://mysite.com/foo=http%3A%2F%2Fabc.com%2Fmy%20page.html%3Fname%3Dbob%26foo%3Dbar

Notice how both URLs have a query string parameter foo but that's OK because the encoded URL has that encoded. The entire foo parameter is

http%3A%2F%2Fabc.com%2Fmy%20page.html%3Fname%3Dbob%26foo%3Dbar

There is no conflict with the foo=bar in the second, encoded, URL.

encodeURI

Now, if you want to encode a complete URL that you have already, use encodeURI.

encodeURI('http://abc.com/my page.html?name=bob&foo=bar')

Will give you

"http://abc.com/my%20page.html?name=bob&foo=bar"

Notice how that keeps the URL valid and, in this instance, only encodes the space. If you were to run encodeURIComponent on that, you'd get the mess you see in my first example.

What characters are encoded?

As yabol commented in your first post, this page shows you the Differences between encodeURI, encodeURIComponent, and escape: lower ASCII characters. You notice specifically that encodeURIComponent encodes the following chars that encodeURI does not:

chr     encodeURI(chr)  encodeURIComponent(chr)
 +           +               %2B
 /           /               %2F
 @           @               %40
 #           #               %23
 $           $               %24
 &           &               %26
 ,           ,               %2C
 :           :               %3A
 ;           ;               %3B
 =           =               %3D
 ?           ?               %3F

Your question

You are correct in using encodeURIComponent because you're encoding a URL for a query string. This goes back to my first example. If your query-string URL (the one you're encoding) has a query string, you want that to be part of next, not part of your main URL.

Wrong

"http://example.com/?next=" + encodeURI('http://abc.com/my page.html?name=bob&foo=bar')
"http://example.com/?next=http://abc.com/my%20page.html?name=bob&foo=bar"

Your example.com url has two query string parameters: next and foo

Right

"http://example.com/?next=" + encodeURIComponent('http://abc.com/my page.html?foo=bar')
"http://example.com/?next=http%3A%2F%2Fabc.com%2Fmy%20page.html%3Fname%3Dbob%26foo%3Dbar"

Your example.com url contains only one query string parameter: next

2 of 3
2

If U need to encode the URI as a query string parameter, then you should definitely go with (2)

var url = "http://example.com/?next=" + encodeURIComponent(query_url);

take for example google translator, whenever you type the address in the Translate Section, The address is converted to a URI Component and then passed on to the google servers

If any URL need to be used as a component, then encodeURIComponent(String); is your best bet