-1

I'm using the following code to display a result passed on by a click tracker in the URL of the webpage. The following goes before the "/head" tag:

<script>    
  function getURLParameter(name) {  
    var query = window.location.search.substring(1);  
    var vars = query.split("&");  
    for (var i=0;i<vars.length;i++) {  
      var pair = vars[i].split("="); 
      if(pair[0] === name){return pair[1];}  
    }  
    return "";
  }
</script>

The following is in the "body" tag to display the result:

 <script>document.write(getURLParameter('name'))</script>

However, the problem is that if the result is two words, the display looks like "Word20%Word"

Can someone help with this please?

Thanks in advance.

nem035
  • 34,790
  • 6
  • 87
  • 99
  • 2
    Possible duplicate of [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – Kosh Dec 30 '18 at 02:11

2 Answers2

2

To make strings with non-url friendly characters such as a space become url-friendly, we encode them.

The browser api used for this is encodeURIComponent.

To decode an encoded string back, we use decodeURIComponent.

const string = 'i have spaces';

const encoded = encodeURIComponent(string);

console.log(encoded);

const decoded = decodeURIComponent(encoded);

console.log(decoded);
nem035
  • 34,790
  • 6
  • 87
  • 99
0

You want to check out decodeURIComponent(), which is responsible for decoding those entities (%20 etc) back into their appropriate counterparts:

function getURLParameter(name) {  
    var query = window.location.search.substring(1);  
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {  
        var pair = vars[i].split("="); 
        if(pair[0] === name){return decodeURIComponent(pair[1]);}  
    }  
    return "";
}
Blue
  • 22,608
  • 7
  • 62
  • 92