lastIndexOf for URL - javascript

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

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)

How to change referrer link?

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.

Replacing an onclick event on a hyperlink with a slightly altered function

My problem at the moment is that I have a email hyperlink on a page that opens up a new email pop-up screen. Each time the email link is clicked, the To: field in the email pop up will get populated by the email address attached to the hyperlink. If that email has an apostrophe in it, the first time it is clicked it will work ok, but each time after it will change the apostrophe for '%27' (as seen in picture below).
The idea in my script here is to put all of the links in the page into an array, search through that array for the one with the class of "EMAILLINK" and replace the onclick event on that link with a function of my own, which removes the '%27' in the link and puts in an apostrophe.
<script>
// When the page loads
$(document).ready(function () {
// Load all of the link elements into an array
var allLinks = document.getElementsByTagName('a');
// Iterate through all of the links on the page
for (var i=0; i<allLinks.length; i++) {
// When you find one with a class of "EMAILLINK" (an email link)
if (allLinks[i].className=="EMAILLINK") {
// Load the text of the onclick event into a car
var strOldOnclick = allLinks[i].onclick + '';
// Create a regex that matches a single quote, along with part of the function
// used to launch the email pop-up
var testRegex = /(MailTo\(\'.*\%27.*\',event,.*\))/gi;
// Check if the link contains an encoded single quote
if (testRegex.test(strOldOnclick)) {
// Execute the regex against the onclick event
// (loads part of it into variable 1 (RegExp.$1))
testRegex.exec(strOldOnclick);
// Replace the correct onclick text in your string var
var newFunc = "alert('NewFunc running'); if(parent&&parent.frames['EWARE_MENU'])fn=parent;"
+ "else fn=opener.parent;"
+ "if(fn&&fn.frames['EWARE_MENU'])"
+ "fn.frames['EWARE_MENU']."
+ RegExp.$1.replace('%27', "\\'") +";"
// Replace the onclick event for the link with the updated value
$("Before test: " + [allLinks[i]]).attr('onclick','').unbind('click');
$([allLinks[i]]).bind("click", Function(newFunc));
}
}
}
});
</script>
This is the original onclick event on the link when I view the source of the page:
if(parent&&parent.frames['EWARE_MENU'])fn=parent;else fn=opener.parent;if(fn&&fn.frames['EWARE_MENU'])fn.frames['EWARE_MENU'].MailTo('R%27Sakai#demo.com',event,'&Key0=3&Key1=116&Key2=169');
Note: I know the onclick is getting changed correctly as the alert is coming up when I click on the link, so it is something to do with the way I have changed the Javascript in (var newfunc)
A variation of this works in Internet Explorer but not in Chrome (or Firefox) and that is where it is going to be used.
You do not need to write a function of your own, just use the JavaScript unescape() function to remove the apostrophe. If MailTo contains the string with the apostrophe:
var readableString = unescape(MailTo);

Change the pathname in the URL of a link while keeping the querystring constant

From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)

Categories