Reputation: 476
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, ' ')
Upvotes: 0
Views: 133
Reputation: 3382
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
Upvotes: 0
Reputation: 5749
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, ' ')
Upvotes: 3