NGinCreator NGinCreator - 6 months ago 15
HTML Question

Replacing + with a space

I'm trying to set text in a div according to variables in the URL set via GET. I can only do it this way as this is for a JavaScript assignment so no servers around. As URLs tend to do, spaces in a string have been replaced by a

+
.

str.replace("+"," ")
does absolutely nothing. I found some other links on this site that use a simple
/+/g
instead, but on my code it makes my entire output disappear.

Initial implementation (already replacing %20 with a space for email):
http://imgur.com/TaJo6SA

With the str.replace code:
http://imgur.com/RgmcjnF

Here is the code (function found at css tricks):

function getQueryVariable(variable){
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] == variable){return pair[1];}
}
return(false);
}

str = getQueryVariable("address");
var address = address.replace(/+/g," ");
document.getElementById('address').innerHTML = "Your postal address: " + address;

Answer

I modify your function:

function getQueryVariable(variable){
        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] == variable){
            return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
          }
        }
        return(false);
   }

Now it returns parsed data(without any urldecoded parts).