So let's say there's a URL http://example.com/index.html/hello/hi where "hello" and "hi" are parameters.
How would you use javascript and forms method POST to extract the parameters?
Your subject is a little bit vague. However, I thought I'd made an example of possibilities.
http://jsfiddle.net/tive/LjbPq/
The idea is to split the URL for each character /, in whatever way you received it.
var parts = document.URL.split("/");
Since split() returns an array (zero based), you need to distract 1 from the total length to get the last index.
var lastPart = parts[parts.length - 1];
Run this in a for loop, and you should get the idea as occurring in the example.
documentation on document.URL to retreive the complete URL
documentation on window.location to use properties of a url (protocol, href, pathname, ...)
this could work...
var secondvar = window.location.href.split('/')[window.location.href.split('/').length];
var firstvar = window.location.href.split('/')[window.location.href.split('/').length-1];
Related
I've got a CSJ variable to capture the last parameter of the URL. Given I'm interested on capturing the location and its position may vary (see example below), I managed to create a custom variable that will always give me the last parameter in the URL.
URL examples:
https://www.example.co.nz/location/**holmwood**
https://www.example.co.nz/find-a-location/auckland/**central-auckland**
The issue I'm having is that my script (see below) is not only capturing the last parameter of the URL, but any string after the "?" symbol, which are mainly UTMs.
Code:
function(){
var pageUrl = window.location.href;
return pageUrl.split("/")[pageUrl.split("/").length - 1];
}
So, on my GA view instead of seeing the ph + the location, I see a large string:
I know I could use page path and remove query from there, but for a specific event I'd rather sort that out from the custom variable because of the type of value I'm passing.
What else should I add to my script to keep it completely the same and exclude any query parameters that might be automatically tagged?
Thanks.
Rather than returning the first split, I would then put it through an additional one where you are splitting on the '?'
function(){
var pageUrl = window.location.href;
var lastSlash = pageUrl.split("/")[pageUrl.split("/").length - 1];
return lastSlash.split("?",1);
}
What is the best way to get the last two URL segments?
To get the last segment is pretty easy url.substr(url.lastIndexOf('/') + 1)
Here is an example, say I have this url http://mywebsite/segment1/segment2
So I want to get segment1/segment2
Is there a better way than just using url.split("/");?
Splitting, slicing and joining is probably the easiest:
const url = 'http://mywebsite/segment1/segment2';
const lastTwo = url.split('/').slice(-2).join('/');
console.log(lastTwo);
You can use this as a reference :
Take out the pathname, and then do the string.split, it would also protect you from the content after the ? sign (url parameters).
What I'm trying to do is fetch a single piece of a string without using the hashtag element in the url. I already have a functioning code but it needs altering. So, how do I fetch any part of the url after ?.
Say I have ?fx=shipment+toys/fish-fix-fx/ as my url string; I want the button to show if shipment or fish or fx was my choice of selections for example.
Buttons showing with hastag: http://jsfiddle.net/66kCf/2/show/#iphone
Original JSFiddle (buttons not showing): http://jsfiddle.net/66kCf/2/
I want the iPhone buttons to show if fix was my choice: http://jsfiddle.net/66kCf/2/show/?fx=shipment+toys/fish-fix-fx/
try doing it with .split() and.match() like this...
var keys = window.location.href.split('?');
if (keys[1].match(/(fix|fish|fx)/))
{
$("#linkdiv").append(nextLink);
$("#linkdiv1").append(nextLink);
$("#linkdiv2").append(nextLink);
}
demo button showing : http://jsfiddle.net/LbKmf/show/?fx=shipment+toys/fish-fix-fx/
demo button not showing: http://jsfiddle.net/LbKmf/show/?reigel
Is this what your looking for:
"?fx=shipment+toys/fish-fix-fx/".split(/[\?=+\/-]/g);
window.location.search and split into array for comparisons
explained in How can I get a specific parameter from location.search?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Generally, Javascript doesn't have a built-in functionality for query string parameters. You can use string manipulation on window.location.search to get your parameters out of the URL string. Note that location.search includes the ? character too.
Something like this should do:
var queryString = function () {
// Anonymous function - executed immediately
// get rid of the '?' char
var str = "?fx=shipment+toys/fish-fix-fx/";
var query = str.substring(str.lastIndexOf('=')+1,str.indexOf('/'));
var vars = query.split("+");
for (var i=0;i<vars.length;i++){
console.log(vars[i]);
}
return vars;
} ();
I have some Javascript that parses out the name of a site so that I can query an XML file to pull data where the node's attribute is the last part of a URL.
<script>
function myExampleSite()
{
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
return result;
}
var exampleSite = myExampleSite();
</script>
For example, if the site is http://myexamplesite.com/status-Blah00 I would be able to get all data out of the Blah00 XML node and populate various aspects of the site with whatever is in the XML.
This works fine and I am able to use the URL name (Status-Blah00, Status-Blah01, etc.) to query XML against it and populate elements on the page based on the name of the site.
However I ran into problems where a site has a second - in the URL.
For example:
http://myexamplesite.com/status-Blah01-Blah00.htm
It should be parsing the Blah01-Blah00 node of my XML, but instead of just gets the data from Blah00 since it doesn't recognize the first -. I'm new to javascript and I'm confused as to how to basically do:
if 1 "-" in url then get last index
else the number of "-" in url is > 1, get first index.
How would I be able to count the number of "-" in the URL and logically do just that with the above Javascript?
You could use a regex for this problem. Here is a start:
"status-Blah01-Blah00.htm".match(/([^-]+)/g)
That code generates the array:
["status", "Blah01", "Blah00.htm"]
So you can work with the length of that array to find out how many hyphens are in the url.
Even easier: "status-Blah01-Blah00.htm".split('-') returns the same array.
Here is a single line with sequential regexes that can handle dashes occurring elsewhere in the url and that keeps the Blah01-Blah00 node as a single string rather than separating them, as it seems you requested.
"http://www.site-name.com/folder-name/01-10-20/status-Blah0100-Blah01.htm".match(/-([^.\/]+)\.htm/g)[0].match(/[A-z0-9][A-z0-9\-]+/g)[0]
Generates:
"Blah0100-Blah01"
I'm using javascript and would like to take a URL string that I have and break it down into its components such as the host, path, and query arguments.
I need to do this in order to get to one of the query arguments, which is itself a URL and is thus encoded in the original URL string.
I feel like there should be an easy way to do this in Javascript. Perhaps something that looks like this:
var what_I_Want = url("http://www.domain.com?queryArg1=somequeryargument").getQueryArgumentValue("queryArg1");
The parseUri function will do everything you need
Edit
Alternatively you can get the DOM to do the hard work for you and access properties on a newly created a object for different parts of the URL.
<script type="text/javascript" language="javascript">
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>
Hope this will help..
In javascript you can do this by using split() for the params and using the location object for the protocol and domain -- like Carl suggested
Also you can use parseUri as Tak suggested
There is also a jQuery plugin which makes parsing easier if you are already using jQuery in your project: https://github.com/allmarkedup/jQuery-URL-Parser#readme
Example:
$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'
Probably not the greatest way of doing it but a simple method to get the query string in JavaScript would be to just use something along the lines of:
a = "http://www.domain.com?queryArg1=somequeryargument";
query = a.substring(a.indexOf('?')+1);
You could then split the query up based on the &'s and again on the = to get at whatever param you need.
Sorry if this ain't very helpful as its a bit of a low tech method :P
EDIT:
Just wrote a quick little JavaScript object to get URL Query parameters for you (sort of like) in your example. Only tested it in chrome but in theory it should work :)
//Quick and dirty query Getter object.
function urlQueryGetter(url){
//array to store params
var qParam = new Array();
//function to get param
this.getParam = function(x){
return qParam[x];
}
//parse url
query = url.substring(url.indexOf('?')+1);
query_items = query.split('&');
for(i=0; i<query_items.length;i++){
s = query_items[i].split('=');
qParam[s[0]] = s[1];
}
}
//Useage
var bla = new urlQueryGetter("http://www.domain.com?queryArg1=somequeryargument&test=cheese");
alert(bla.getParam('test'));