skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Using the code from the OP’s question:

    const url = new URL("http://example.com");
    url.searchParams.append("name", "Mustermann");
    url.searchParams.append("question", "how does the URL.toString() function work?");
    

    Output of encodeURI(url):

    http://example.com/?name=Mustermann&question=how+does+the+URL.toString%2528%2529+function+work%253F
    

    Output of url.toString():

    http://example.com/?name=Mustermann&question=how+does+the+URL.toString%2528%2529+function+work%253F
    

    Output of encodeURIComponent(url):

    http%3A%2F%2Fexample.com%2F%3Fname%3DMustermann%26question%3Dhow%2Bdoes%2Bthe%2BURL.toString%2528%2529%2Bfunction%2Bwork%253F
    

    The output of encodeURI(url) and url.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. The encodeURI 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search