How to change referrer link? - javascript

How to convert this link 1 to the destination link 2 with Javascript. The second link is the actual destination of the original link1.
Update: I am given the link in the first link form, but I want it in the second form because I need to get Ajax request with the second link form.
original link
actual link

You cannot extract the full link, because The Guardian provides a shortened URL. The best thing you can do is to extract the shortened URL using substr and then apply decodeURIComponent:
function extractFacebookUrl(u) {
u = u.substr(u.indexOf('l.php?u=') + 8); // remove before ?u=
u = u.substr(0, u.indexOf('&')); // remove after &
return decodeURIComponent(u);
}
var link = "https://www.facebook.com/l.php?u=http%3A%2F%2Fgu.com%2Fp%2F4dqfm%2Ffb&h=VAQHJLcqT&enc=AZPaThEaRTCX-l4-p7IhnG-fLwffa6Gc29biVbxjLL_bwGigUa4xy6V1OwJKFCslcpd0qbSIDYtTBVOEovtYW2k2B37re6-kaQuraywUr_DNQcEm5MG8Cc9ODb8hfOZ5CuNoTYvIT7VxpMSwHDS1k-eChZ9vc3USJLAsoB0ZmFBOZmFQKd6o8n_SKadD6295xn5d6Q7_URlDDqw-7pjapUuZ&s=1";
document.body.innerText = extractFacebookUrl(link);
It returns http://gu.com/p/4dqfm/fb, which leads to the actual page.
Note that it supposes that original link has always the same format and the order of GET arguments.

Related

How to link to the current URL + 1 using JavaScript?

I'm looking to create a simple nav link that goes to the next or previous page in a series. The URL ends in a number and each successive page is just the next number in the sequence (.../101, /102, /103, etc). Is there a way to use javascript to link to the current URL + or - 1?
I know basically no javascript besides what I can copy and paste into HTML.
How do I solve this problem?
You need to take location.href, take pathname, split it and increment the last item with the value. Then join and assign to the pathname. Finally append the element to the body (or any other location).
Further readings:
Location all about <a>
document.location where you get the actuall href
var url = document.createElement('a'),
pathes;
url.href = 'http://example.com/123'; // or at the site: location.href
url.appendChild(document.createTextNode('link'));
pathes = url.pathname.split('/');
pathes[pathes.length - 1] = +pathes[pathes.length - 1] + 1;
url.pathname = pathes.join('/');
document.body.appendChild(url);

Built relative URL in pages that are missing trailing slash /

We desperately need help with writing a small code that allows you to take the current page URL and the parameter in the href="parm" and create the link by joining the two with a slash.
The reason we need to do this is because we need relative links to the current page. The CMS system that we are working removes trailing slash from the end of URL.
Which is a problem because if you are at a page
domain.com/fruit/apple
and create a link such as href="calories" or href="./calories"
it will point to domain.com/fruit/calories
Instead, we want it to point to
domain.com/fruit/apple/calories
Which is relative to the current page.
We don't want to change the way that our CMS works, therefore, the need JS solution.
Below you can see one example of what we are trying to accomplish but this only works on one link.
link
Start JS
var x = window.location.href; // Current page URL
var link = document.getElementById("relurl"); // store the element
var curHref = link.getAttribute('href'); // Get HREF paramter
link.setAttribute('href', x + "/"+ curHref);
End JS
The idea is to build relative links every time links with id="relurl" is used.
As per previous example this link: a href="home" id="relurl" target="_blank" title="This is a relative link!">link
at this page: domain.com/fruit/apple
it should point to domain.com/fruit/apple/home
Meaning the link structure is the currentpageURL + / + href
One page may have multiple relative links.
Thanks for any help.
While you could just use relative URLs in your links (with href="./page"), it sounds like the problem is that you are using duplicate IDs (which results in invalid markup). You can test that you have valid markup with the W3C Markup Validation Service.
When you have duplicate IDs, JavaScript only applies to the first element. This can be seen in the following:
var x = window.location.href; // Current page URL
var link = document.getElementById("relurl"); // store the element
var curHref = link.getAttribute('href'); // Get HREF paramter
link.setAttribute('href', x + "/" + curHref);
Working Link
<br />
NOT Working
To resolve this, you should use classes instead of IDs for your links. You can then use document.getElementsByClassName to select the elements. Remember that this returns a NodeList collection of elements, so you'll need to set the new URLs inside of a loop, as can be seen in the following:
var x = window.location.href; // Current page URL
var links = document.getElementsByClassName("relurl"); // store the elements
for (var i = 0; i < links.length; i++) {
var curHref = links[i].getAttribute('href'); // Get HREF paramter
links[i].setAttribute('href', x + "/" + curHref);
}
Working Link
<br />
Another Working Link
Hope this helps! :)
This will update all links in the current page:
const updateNode = node =>
node.href = `${window.location}/${node.href}`
document.querySelectorAll('a').forEach(updateNode)

lastIndexOf for URL

So, I have the following script:
<script>
var id = window.location.href
var buttonText = id.substr(id.lastIndexOf('/') + 1);
jQuery("#first_button").html(buttonText)
</script>
So, what it does is that it replaces text of "id=first_button" button with the url next to the last "/".
Here is the set up of URL for my site: mysite.com/first/second/
The problem is that, all my pages end with "/" (ex. .com/something/something/something/).
So, the nothing shows up as there is nothing after the last "/"
Here is what I am trying to achieve essentially.
I have two buttons: First button and Second Button.
And the URl of any pages will follow the same format: `.com/first/second/.
I am trying to replace the first button with /first/ URL and second button with /second/ URL as shown below.
In summary, the code that I have right now only changes the first button text by the URL after the last "/".
I want the URL between first and second "/" (such as ".com/first/") to replace the first button title.
I want the URL between the second and third "/" (such as".com/first/second/") to replace the second button.
In jQuery, how can I target the specific URL section?
Thanks bunch!
You seem to want this :
var parts = window.location.href.split('/').filter(Boolean);
jQuery("#second_button").html(parts.pop());
jQuery("#first_button").html(parts.pop());
split('/') makes an array from the href, pop() takes the last element of that array.
You can also do it with a regular expression:
var m = window.location.href.match(/([^\/]+)\/([^\/]+)\/?$/);
if (m) {
jQuery("#first_button").html(m[1]);
jQuery("#second_button").html(m[2]);
}
If you don't want the two last parts of the href but the two first parts of the path, do it like this:
var m = window.location.pathname.match(/([^\/]+)\/([^\/]+)/);
if (m) {
jQuery("#first_button").html(m[1]);
jQuery("#second_button").html(m[2]);
}

Rewrite links from an array

I have 2 index pages with approx. 150 links on each. I would rather maintain 1 page and just generate the links dynamically based on a variable value. For example create a list of links. link1, link2, link3... and based on a variable value being 'true' replace those links with list of alternate links i.e. altlink1, altlink2, altlink3...
I have figured out how to do this once but rather than writing the same code over and over for each link I was wondering if there was a faster way. Like creating a list "a" and corresponding list "b" or something like that. I have included my current code below and I look forward to your advice.
<script type="text/javascript">
// link rewriter
var hostadd = location.host;
var vendor = '999.99.999.99';
var localaccess = 'somesite.com';
$(document).ready (
function link_switcher(){
//if not a vendor route to alternate website
if (hostadd != vendor) { $("a[href= 'https://www.somelink1.com']").attr ('href', 'https://www.alternatelink1.com') }
});
</script>
is it possible to create an array and then javascript that would say replace link1 in array a with alternatelink1 in array b?
It's still not entirely clear what you're trying to do, but if you want to rewrite all links based on a lookup table that tells you what link to convert to what, here's how you could do that:
// Table of links.
// Key is original page source URL
// Data is link to change it to
var linkData = {
"http://www.google.com": "http://www.bing.com/",
"http://mail.google.com/mail/?shva=1#inbox": "http://www.hotmail.com"
};
// find every link in the page and change it if it's value is found in the linkData table
$("a").each(function() {
var link = this.getAttribute("href"); // use getAttribute to get what was actually in the page, perhaps not fully qualified
if (linkData[link]) {
this.href = linkData[link];
}
});
If the link is not found in the table, it will not be modified. If there was some pattern to the modification, it might be possible to code that pattern and not have to list every link in the table, but you haven't shared any info about a pattern.
And, a working jsFiddle example: http://jsfiddle.net/jfriend00/Cvj8C/.

How to Execute Javascript Code Using Variable in URL

I'm really new to Javascript and I'm having some trouble understanding how to get the following to work. My goal is to have a certain Javascript action execute when a page loads and a variable added to the end of the URL would trigger which Javascript action to execute. The URL of the page that I'm looking to implement this on is http://www.morgantoolandsupply.com/catalog.php. Each of the "+expand" buttons, which are Javascript driven, drop-down a certain area of the page. Ultimately, I would like to be able to create a URL that would automatically drop-down a certain category when the page loads. Could anybody explain to me the process to do this? Thanks in advance for any help!
You have to parse the URL somewhat "manually" since the parameters in the url aren't automatically passed to javascript, like they are in server-side scripting (via $_GET in PHP, for instance)
One way is to the use the URL fragment identifier, i.e. the "#something" bit that can go at the end. This is probably the neatest way of doing it, since the fragment isn't sent to the server, so it won't be confused with any other parameters
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if( window.location.hash ) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
The URL "http://www.morgantoolandsupply.com/catalog.php#1" would thus automatically expand the "toggle1" element.
Alternatively, you can use a normal GET parameter (i.e. "?foo=bar")
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if( parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search contains the parameters, i.e. everything from the question mark to the end or to the URL fragment. If given the URL "example.com/page.php?expand=foo", the parameter[1] would equal "foo". So the URL "http://www.morgantoolandsupply.com/catalog.php?expand=1" would expand the "toggle1" element.
I'd perhaps go for something more descriptive than just a number in the URL, like, say use the title of the dropdown instead (so "#abrasives" or "expand=abrasives" instead of "#1" or "expand=1"), but that would require a little tweaking of your existing page, so leave that for later
You've already got the function to call: toggle2(), which takes two parameters that happen to be identical for all categories except for a number at the end. So create a URL that includes that number: http://www.morgantoolandsupply.com/catalog.php#cat=4
Then find that number in location.hash using a regular expression. This one is robust enough to handle multiple url parameters, should you decide to use them in the future: /[\#&]cat=(\d+)/. But, if you expect to never add anything else to the url, you could use a very simple one like /(\d+)/.
Once you've got the number, it's a simple matter of using that number to create your two parameters and calling toggle2().
This should work:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}
Not a complete answer ("Give a man a fish" and all that), but you can start with something along these lines:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
More info on window.location is available from the Mozilla Developer Network.
Having said that, given that you're talking about a PHP page why don't you use some server-side PHP to achieve the same result?

Categories