Reputation: 1199
I have a URL string like http://www.example.com/?chicken?toast
And I want to be able to store the values after each of the ? characters.
I have it working getting the last ?value - but cant seem to store the first...
Code that works to get the last ?value is:
window.lastValue = window.location.href.substring(window.location.href.lastIndexOf('?') + 1);
How can I store the first also?
So firstValue = chicken and lastValue = toast
UPDATE - How can I also store a totalVal by flattening the array? So, if the array was ["chicken", "toast"] I need this flattened into a string with a "." before each item in the array - so if the array was ["chicken", "toast"] it would become ".chicken.toast" - if the array was ["chicken"] it would become ".chicken" // thanks
Cheers,
Upvotes: 0
Views: 34
Reputation: 6742
This will give you an array of the values you want:
var r = window.location.href.split("?");
r.shift();
console.log(r);
If there are always exactly two values, you can use this to extract them:
var val1 = r.shift();
var val2 = r.shift();
Here's a version which gives the .chicken
result:
var r = window.location.href.split("?");
r[0]='';
var totalval = r.join('.');
Upvotes: 1
Reputation: 253318
I'd suggest:
// obviously, in production you should use document.location.href:
var url = "http://www.example.com/?chicken?toast",
// take a substring of the url variable, starting at the index of
// the (first) '?' character and running to the end of the string,
// giving "?chicken?toast", we then split that resultant string
// on the '?' characters, and filter the resulting array using
// filter(Boolean), which retains only the true/truthy array-elements:
values = url.substring(url.indexOf('?')).split('?').filter(Boolean);
console.log(values);
var url = "http://www.example.com/?chicken?toast",
values = url.substring(url.indexOf('?')).split('?').filter(Boolean);
console.log(values);
You could, instead, use document.location.search
to retrieve the substring from the first '?'
onwards (if using document.location.href
).
References:
Array.prototype.filter()
.String.prototype.indexOf()
.String.prototype.split()
.String.prototype.substring()
.Upvotes: 1
Reputation: 8720
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
// Do something with the name sParameterName[0]
// Do something with the value sParameterName[1]
}
This reference may be of some use to you: http://www.jquerybyexample.net/2012/06/get-url-parameters-using-jquery.html
Upvotes: 0