Search code examples
javascripturldecoding

Issue with Decoding %20 from URL


I have found that the following thread provides an extremely useful way to create permalinks or to pass string values via a URL:

Original Thread

Unfortunately, if you wanted to pass the string "test string", for example, to a specific <div> via the URL and display it as simple text, the above thread doesn't seem to decode white space if your URL looks like this:

http://www.abc123.org/subpage.html?test%20string

The code will simply take anything in the URL passed the "?" and it will appear as "simple%20text".

Is there a simple way to do something similar to the Thread's accepted answer so that all %20 can be replaced with white space? Thanks!


Solution

  • You can use decodeURI():

    Replaces each escape sequence in the encoded URI with the character that it represents, but does not decode escape sequences that could not have been introduced by encodeURI. The character “#” is not decoded from escape sequences.

    const result = decodeURI('http://www.abc123.org/subpage.html?test%20string');
    
    console.log(result);