Question

I'm wanting to get data from the URL query string and display it in the body of an HTML document. I can't get the script to replace the + signs with an empty space.

Example URL: www.mywebsite.com/?item=Sandwich&bread=White+Bread

In the HTML body, the text field for item would show "Sandwich" but the text field for bread would show "White+Bread." How can I replace the + with a space?

Here's the function Im using to get value from the URL

function querystring(key) {
    var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
    var r=[], m;
    while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
    return r;
}

    $("span.item").text(querystring('item'));
    $("span.bread").text(querystring('bread'));

I've tried using this but it's telling me arrays don't have a replace function.

.replace(/\+/g, ' ')
Was it helpful?

Solution

Your function returns an array, try changing it by this:

function querystring(key) {
    var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
    var r=[], m;
    while ((m=re.exec(document.location.search)) != null) r.push(m[1]);
    return r[0];
}

then you can use your replace

.replace(/\+/g, ' ')

OTHER TIPS

I'd replace your function with something like this, getting rid of the regular expression for the sake of readability. It handles undefined keys/values, plus you could easily refactor the first part of it into a parseQueryString function returning a dictionary for the current document.location.search.

function querystring(key) {
   var hash = {};

   var pairs = document.location.search.substr(1).split('&');
   for(var i = 0; i < pairs.length; i++) {
       var tuple = pairs[i].split('=');
       hash[tuple[0]] = tuple[1];
   }

   var val = hash[key];
   return (val) ? val.replace(/\+/g, ' ') : undefined;
}

Usage:

querystring('bread');
> White Bread
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top