What I'm trying to do is to change the last character of a link using jQuery or Javascript.
The link that the client will input into the CMS looks something like this: https://www.dropbox.com/sh/wbc1ewhfg1jttpr/AADLfZKlfOBs5e_ueAkzffKRa/SamplePDFDownload.pdf?dl=0
What I'd like to do is to set the website to take this link and replace the '0' on the end of the link with a '1'.
Does anyone know how this could be done automatically?
Any help is appreciated,
Tom
As easy as that:
var url = document.getElementById("id of element").href;
url = url.substring(0, url.length-1);
url = url + "1";
document.getElementById("id of element").href = url;
Probably google first about string functions before asking...
If the pattern of the url stays the same (the parameter dl=0) then you can simply use the .replace()-function:
var url = 'https://www.dropbox.com/sh/wbc1ewhfg1jttpr/AADLfZKlfOBs5e_ueAkzffKRa/SamplePDFDownload.pdf?dl=0';
url = url.replace('dl=0', 'dl=1');
Related
I want to get the my exact location (only PHP page) using javascript, I'm currently using window.location to get the exact url for example: localhost/empc/myfolder/functions.php what is the code if I want to get only functions.php as a result? Is it possible? Thank you.
You can use location object to do this, To remove the "/" before the file name you can use substring method.
location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
you can try this pretty simple
var url = 'localhost/empc/myfolder/functions.php';
var url = url.split('/');
alert(url.pop());
It is possible. Use the javascript split function to separate the string into pieces and then access the last element to get the file name:
var str = "localhost/empc/myfolder/functions.php";
var arr = str.split("/");
alert(arr[arr.length-1]); //this will alert functions.php
I'm trying to build an URL in jquery and then open it. The problem is that the URL should contain an ampersand and I can't figure out how to do that
var url = 'print?month=' + jQuery('#month').val() + '&year=' + jQuery('#year').val();
var encodedUrl = encodeURIComponent(url);
window.open(encodedUrl);
Essentially, what I'd like the URL to be is: print?month=1&year=2015
Yes, changing & a m p ; [without spaces] to & should work, if not you should probably do something like below:
var url = 'print?month=' + encodeURIComponent(jQuery('#month').val()) + '&year=' + encodeURIComponent(jQuery('#year').val());
window.open(url);
Fully working plnkr is at:http://plnkr.co/edit/70h1E8SJDXMhtMJPnKMp?p=preview
Just enable popups on your browser for plnkr if you dont see the popup yet.
Basically just create a string with concatenating & charecters, its just a string, you dont need to URIEncode it, then do a window.open of the string. That should do it.
I have for example, https://www.example.com/test1/something?asd=1. Of this example URL I need to grab everything up until and included /test1/. So I would set var url = https://www.example.com/test1. The problem is that test1 is dynamic so I can not have any hard coded values.
How can I do this?
One way is to use a combination of split() and join():
var url = "https://www.example.com/test1/something?asd=1";
var result = url.split("/",4).join("/");
Here's a JSFiddle of it in action:
http://jsfiddle.net/msm3jsvw/
Need help! I've been looking for a solution for this seemingly simple task but can't find an exact one. Anyway, I'm trying to add custom #id to the tag based on the page's URL. The script I'm using works ok when the URLs are like these below.
- http://localhost.com/index.html
- http://localhost.com/page1.html
- http://localhost.com/page2.html
-> on this level, <body> gets ids like #index, #page1, #page2, etc...
My question is, how can I make the body #id still as #page1 or #page2 even when viewing subpages like this?
- http://localhost.com/page1/subpage1
- http://localhost.com/page2/subpage2
Here's the JS code I'm using (found online)
$(document).ready(function() {
var pathname = window.location.pathname;
var getLast = pathname.match(/.*\/(.*)$/)[1];
var truePath = getLast.replace(".html","");
if(truePath === "") {
$("body").attr("id","index");
}
else {
$("body").attr("id",truePath);
}
});
Thanks in advance!
edit: Thanks for all the replies! Basically I just want to put custom background images on every pages based on their body#id. >> js noob here.
http://localhost.com/page2/subpage2 - > my only problem is how to make the id as #page2 and not #subpage2 on this link.
Using the javascript split function might be of help here. For example (untested, but the general idea):
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
$('body').id = segments[0];
Also, you might want to consider using classes instead of ID's. This way you could assign every segment as a class...
var url = window.location.href.replace(/http[s]?:\/\//, '').replace('.html', '');
var segments = url.split('/');
for (var i = 0; i < segments.length; i++) {
$('body').addClass(segments[i]);
}
EDIT:
Glad it worked. Couple of notes if you're planning on using this for-real: If you ever have an extension besides .html that will get picked up in the class name. You can account for this by changing that replace to a regex...
var url = window.location.href.replace(/http[s]?:\/\//, '');
// Trim extension
url = url.replace(/\.(htm[l]?|asp[x]?|php|jsp)$/,'');
If there will ever be querystrings on the URL you'll want to filter those out too (this is the one regex I'm not 100% on)...
url = url.replace(/\?.+$/,'');
Also, it's a bit inefficient to have the $('body') in every for loop "around" as this causes jQuery to have to re-find the body tag. A more performant way to do this, especially if the sub folders end up 2 or 3 deep would be to find it once, then "cache" it to a variable like so..
var $body = $('body');
for ( ... ) {
$body.addClass( ...
}
Your regex is only going to select the last part of the url.
var getLast = pathname.match(/./(.)$/)[1];
You're matching anything (.*), followed by a slash, followed by anything (this time, capturing this value) and then pulling out the first match, which is the only match.
If you really want to do this (and I have my doubts, this seems like a bad idea) then you could just use window.location.pathname, since that already has the fullpath in there.
edit: You really shouldn't need to do this because the URL for the page is already a unique identifier. I can't really think of any situation where you'd need to have a unique id attribute for the body element on a page. Anytime where you're dealing with that content (either from client side javascript, or from a scraper) you should already have a unique identifier - the URL.
What are you actually trying to do?
Try the following. Basically, it sets the id to whatever folder or filename appears after the domain, but won't include a file extension.
$(document).ready(function() {
$("body").attr("id",window.location.pathname.split("/")[1].split(".")[0]);
}
You want to get the first part of the path instead of the last:
var getFirst = pathname.match(/^\/([^\/]*)/)[1];
If your pages all have a common name as in your example ("page"), you could modify your script including changing your match pattern to include that part:
var getLast = pathname.match(/\/(page\d+)\//)[1];
The above would match "page" followed by a number of digits (omitting the 'html' ending too).
How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?
you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.
With location and any link (<a>) elements on the page, you get a load of properties that give you specific parts of the URL: protocol, host, port, pathname, search and hash.
You should always use these properties to extract parts of the URL in preference to hacking about with href and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query or #fragment is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a / character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();
Most of the solutions here are not taking advantage of the window.location object. The location object has this wonderful thing called pathname which returns just the path, no query string, host, protocol, hash, etc.
var mypage = window.location.pathname.split("/").pop();
You could do something like this:
document.location.href.split('/').pop();
Edit: you probably want to get rid of the query string if there is one also:
document.location.href.split('/').pop().split('?').shift();
Edit 2: this will also ignore an anchor in the url if there is one
document.location.href.split('/').pop().split(/\?|#/).shift();
This should also exclude query and hash values.
var path = location.href;
path = path.substring(path.lastIndexOf("/") + 1);
path = path.split("?")[0].split("#")[0];
console.debug(path);
Haven't tested so compeltely guessed, but I'm sure something like this will do :-)
var url = 'http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html';
var page = url.split('/');
alert(page[page.length-1]);
EDIT Tested under jsfiddle and it was wrong, the above code should now work :-)