I have the following example code:
const url = new URL("http://example.com");
url.searchParams.append("name", "Mustermann");
url.searchParams.append("question", "how does the URL.toString() function work?");
window.open(url.toString(), '_self');
My question is does the URL encode the different searchParams?
If it encodes the URL what function does it use?
Is the encodeURI() Function or the encodeURIComponent() Function used or is it something different.
2
Answers
Yes, the URL object automatically encodes the values of the search parameters when you use methods like
append()
.It uses a similar encoding to
encodeURIComponent()
where it percent-encodes special characters to ensure that the URL is valid and doesn’t contain characters that might be misinterpreted.For more detail read the documentation on the URL object
Using the code from the OP’s question:
Output of
encodeURI(url)
:Output of
url.toString()
:Output of
encodeURIComponent(url)
:The output of
encodeURI(url)
andurl.toString()
is the same so it’s safe to say that they both serialize the url the same way.The output of
encodeURIComponent
is different because it tries to convert the entire provided string, regardless of whether it’s the protocol part, the query part, or any other part of the url. TheencodeURI
function, on the other hand, expects to get a complete url so it knows it needs to ignore some of the characters like colons and slashes if they’re a part of the url and not the query parameters.