I don't know if it is answered already before. I don't know what to search for.
All I want to know is if there is a jquery function for the following problem.
Let's say I have an URL string like this - www.example.com/a/b/../c
I want to get www.example.com/a/c
One simple way is to create a link element, set its href property, and then read it.
var a = document.createElement("a");
a.href = "http://www.example.com/a/b/../c";
var resolved = a.href;
console.log(resolved); // "http://www.example.com/a/c"
Or using some jQuery:
var resolved = $("<a>").prop("href", "http://www.example.com/a/b/../c").prop("href");
console.log(resolved); // "http://www.example.com/a/c"
Live Example
This works relative to the current document's path, although with the URL above it doesn't matter as the URL is absolute.
Note that it's important that we're using the reflected property, not the attribute, here.
Related
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)
I am trying to get the value of the backgound-image url. The url is set inline directly in the element tag with the style attribute like so
<a style="background-image: url(https:// ....)"></a>
I tried doing
var url = $(this).css('background-image')
with various regexes but it does not seem to work. I am trying to store this URL into MongoDB but I get this error
var styles = parse(el.attribs.style);
TypeError: Cannot read property 'attribs' of undefined
Get the style value, then strip the URL from it
var bi = $('a').css("background-image");
alert(bi.split(/"/)[1]);
The call to jQuery .css("background-image") always returns the URL within double quotes, regardless how it was set originally.
Sample fiddle:
https://jsfiddle.net/6qk3ufcb/
In vanilla JS, having full DOM access, it can be done like so:
document.querySelector('a').style.backgroundImage.split('"')[1]
Or, if for whatever reason you don't have DOM access (for example dealing in node, and operating on some simplified HTML parser) it can also be done with regexp:
const htmlString = `<div class="bg-div" style="background-image: url('https://loremipsum.com/imageIpsum.jpg');">`
const reg = /url.'([\w\W]+?)'/;
const searched = reg.exec(htmlString)
console.log(searched[1]) //=> https://loremipsum.com/imageIpsum.jpg
I have a link like :
<a rel="Test Images" class="thickbox preview_link" href="http://www.localhost.com:8080/testwp/wp-content/uploads/2013/12/2013-10-02_1728.png">
i need to get the url of that image inside a javascript file loaded on the same page.
i tried something like:
image_src = jQuery('a[class=thickbox preview_link]').attr('href');
but all i get is Uncaught Error: Syntax error, unrecognized expression: a[class=thickbox preview_link] in the console.
i am using jquery 1.10.2 on the site
You would do:
jQuery('a.thickbox.preview_link').attr('href');
Your attribute selector syntax is incorrect since it has space you need to wrap them in quotes ('a[class="thickbox preview_link"]'), but you can always use class selector which would be mostly faster than the attribute selector and the order doesn't matter as well.
Just in case you need it, here's the vanilla Javascript version
Get the image(s)
var image = document.getElementsByClassName('thickbox preview_link');
Getting the href (of the first image)
var image_href = image[0].getAttribute('href');
Better version
// Declare the image_href variable
var image_href;
// Getting a nodeList of all the applicable images
var image = document.getElementsByClassName('thickbox preview_link');
// If there's only 1 image and/or you only want the first one's href
if(image[0] !== undefined) {
// if condition to check whether or not the DOM has the images in the first place
// if yes, update the image_href variable with the href attribute
image_href = image[0].getAttribute('href');
}
Best of luck!
thickbox preview_link is actually 2 class tokens, so you're looking for a.thickbox.preview_link or (for that specific attribute) a[class="thickbox preview_link"] (notice the quotes)
image_src = jQuery('a.thickbox.preview_link').attr('href');
// or
image_src = jQuery('a[class="thickbox preview_link"]').attr('href');
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 :-)