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 OverflowencodeURIComponent 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.
Native escape method does that. but also you can create a custom encoder like:
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
this will replace keys used in query strings. further more you can apply it to any other custom encodings by adding needed key-values pairs.
Query-string encoding of a JavaScript object - Stack Overflow
javascript - How to encode URL parameters? - Stack Overflow
javascript - If I am encoding a URI which will be used as a query string parameter: encodeURI or encodeURIComponent - Stack Overflow
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.comTypeScript version for PHP notation (no URL escaped version)
/**
* Converts an object into a Cookie-like string.
* @param toSerialize object or array to be serialized
* @param prefix used in deep objects to describe the final query parameter
* @returns ampersand separated key=value pairs
*
* Example:
* ```js
* serialize({hello:[{world: "nice"}]}); // outputs "hello[0][world]=nice"
* ```
* ---
* Adapted to TS from a StackOverflow answer https://stackoverflow.com/a/1714899/4537906
*/
const serialize = (toSerialize: unknown = {}, prefix?: string) => {
const keyValuePairs = [];
Object.keys(toSerialize).forEach((attribute) => {
if (Object.prototype.hasOwnProperty.call(toSerialize, attribute)) {
const key = prefix ? `${prefix}[${attribute}]` : attribute;
const value = toSerialize[attribute];
const toBePushed =
value !== null && typeof value === "object"
? serialize(value, key)
: `
{value}`;
keyValuePairs.push(toBePushed);
}
});
return keyValuePairs.join("&");
};
Use:
const objectToQueryParams = (o = {}) =>
Object.entries(o)
.map((p) => `${encodeURIComponent(p[0])}=${encodeURIComponent(p[1])}`)
.join("&");
Refer to the below gist for more: https://gist.github.com/bhaireshm
With PHP
echo urlencode("http://www.image.com/?username=unknown&password=unknown");
Result
http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown
With Javascript:
var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);
DEMO: http://jsfiddle.net/Lpv53/
Using new ES6 Object.entries(), it makes for a fun little nested map/join:
const encodeGetParams = p =>
Object.entries(p).map(kv => kv.map(encodeURIComponent).join("=")).join("&");
const params = {
user: "María Rodríguez",
awesome: true,
awesomeness: 64,
"ZOMG+&=*(": "*^%*GMOZ"
};
console.log("https://example.com/endpoint?" + encodeGetParams(params))
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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
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