How to count elements of an href? - javascript

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"

Related

Custom Javascript GTM variable - remove UTMs

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);
}

Redirection Based on Query String

Not wanting to bloat up an .htaccess with 300 entries, what would be the javascript I could use to redirect to URLs based on a query string in the request to this single file. For example,
https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=57
The only part I care about is the 57 and then redirect it to wherever:
https://www.anothercoolwebsite/secretworld/
In the following case, take the 34 and redirect:
https://www.mywebsite.com/redirect.jhtml?Type=Cool&LinkID=34
https://www.anoldwebsite.com/cool/file.html
Thank you!
This should do you fine. Keep in mind a server-side solution like a PHP script will work for more clients. Since you mentioned .htaccess, I think I should let you know about the fallback resource command
Anyways, here is the JS only solution
function parseString(){//Parse query string
var queryString=location.search.substring(1);//Remove ? mark
var pair = queryString.split('&'); //Key value pairs
var returnVal={};
pair.forEach(function(item,i){
var currPair = item.split('=');//Give name and value
returnVal[currPair[0]]=currPair[1];
});
return returnVal;
}
var links=["index", "about"];//Sample array of links, make sure this matches up with your LinkID
location.href=links[parseString().LinkID]+".html"; //Redirect based on LinkID

Javascript post data order

I've got a bit of a funny problem that i'm sure others here will find easy to solve. I need to hash an entire query string, then include that hash value in the post data.
After trying it a few other ways, i'm trying to do this with javascript. Somehow it seems like the order in which the string is pulled together from the form to be hashed differs from the way that it is pulled together when it is submitted.
I'm excluding a hidden element with a specific class to build up the query string to be hashed, then setting that hidden element with the hash value before the final submit.
Any idea what i might be doing wrong, or how i could ensure the order of elements is the same both on building the string and the submit?
The relevant snippet:
var allFormDat = document.getElementById("frmPayment").elements;
var hashingString ='';
var hashVal;
for (i=0;i<allFormDat.length;i++) {
if (allFormDat[i].className!="nohash"){
hashingString+=allFormDat[i].name+'='+allFormDat[i].value+'&';
}
}
hashingString.substring(0, hashingString.length - 1);
hashingString += '[salt]';
hashVal=SHA1(hashingString);
frm.hashValue.value=hashVal;
document.getElementById('frmPayment').submit();
First of all, you're not URI-encoding the components. You probably should:
var field = allFormDat[i];
hashingString += encodeURIComponent(field.name) + '='
+ encodeURIComponent(field.value) + '&';
substring does not work in-place. You'll have to reassign:
hashingString = hashingString.substring(0, hashingString.length - 1);

Using forms and POST method to get URL parameters through Javascript

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];

Appending query strings from multiple pages

I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.

Categories

Resources