I'm looking for a way to retrieve the #anchor part from the current URL with JavaScript.
For example:
http://my-page.com/index.html#contact-us
Would return contact-us.
I could split the URI at the eventual # and then take the last piece, but I'm looking for a somewhat nicer and cleaner suggestion. A native (jQuery?) function would be great, but I guess I'm asking for too much.
Use location.hash:
location.hash.slice(1);
It starts with a #, hence .slice(1). Given an arbitrary string, you can use the built-in URL-parsing feature by creating a <a> element, and set the href, then read other properties, such as protocol, hostname, hash, etc. jQuery example:
$('a').attr('href', url)[0].hash;
location.hash.replace(/^#/, "")
If you work with a variable:
var url = "http://my-page.com/index.html#contact-us";
var hash = url.substring(url.indexOf("#") + 1);
Related
User inputs a web address that I want to get only the tail from, as I do know what site he inputs.
So first I want to remove the "main" URL and get what ever is at the end, so my action is:
Original link: http://example.com/something
var n=e.split("http://example.com/");e=n[1];
And I will get "something"
The problem is that site can also be secured, thus having https not http. Therefore the split wont work.
How do I define a split function, that would work like this:
split("http://example.com/ || https://example.com/")
I do not want to split by looking at "//" or anything of that sort, I want an exact address.
If you like it clear and want to avoid regular expressions, try this:
var n=e.split("http://example.com/",2).pop().split("https://example.com/",2).pop();
If you wish to know the host you can do so by using this code instead in JavaScript:
window.location.host
Source Get The Current Domain Name With Javascript (Not the path, etc.)
You can also use window.location.path to get the URL that was requested, combining those you get:
window.location.host + window.location.pathname
For me, this outputs stackoverflow.com/posts/25203020/edit while writing this reply.
var s = "http://example.com/something";
function split (url) {
var r = /([^:]+):\/\/([^\/]+)\/(.*)/gi;
var a = r.exec(url)
return [a[1], a[2], a[3]];
}
I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:
window.location.protocol
window.location.host
window.location.pathname
but I can't figure out how to do it with document.referrer. Anyone got any ideas?
You can create an a element with the referrer as its url.
a elements (with hrefs) can act like location objects
var a=document.createElement('a');
a.href=document.referrer;
alert([a.protocol,a.host,a.pathname].join('\n'));
a='';
There's no equivalent to window.location with regards to document.referrer so your only option will be to break down the string itself. You could write a regex to do that or rely on a series of string splits:
var parts = document.referrer.split('://')[1].split('/');
var protocol = document.referrer.split('://')[0];
var host = parts[0];
var pathName = parts.slice(1).join('/');
If you want the convenience and can afford the weight, have a look at URI.js or one of the suggested URL parsers. If you don't need anything fancy, <a>s href decomposition will do the job just fine.
I'm using JavaScript to try and get the filename from the URL.
I can get it using this:
var fn=window.location.href.match(/([^/])+/g);
alert(fn[fn.length-1]); // get the last element of the array
but is there an easier way to get it (e.g., without having to use fn[fn.length-1]
Thanks!!
Add a $ at the end so you only get the last part:
window.location.href.match(/[^/]+$/g);
Personally, I try to use simple string manipulation for easy tasks like this. It makes for more readable code (for a person not very familiar with RegEx).
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
Or simply:
var filename = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
Additional Information
Not that it matters for something so trivial, but this method is also more performant than RegEx: http://jsperf.com/get-file-name
How about:
window.location.href.match(/\/([^/]+)$/)[1];
you can use .pop() to get the last element of an array;
alert(fn.pop());
There is a jQuery plugin that makes it easy to parse URLs and provide access to their different parts. One of the things it does is return the filename. Here's the plugin on GitHub:
https://github.com/allmarkedup/jQuery-URL-Parser
I would recommend using that and avoid reinventing the wheel. Regular expressions is an area of programming where this is particularly applicable.
I recommend to also remove any '#' or '?' string, so my answer is:
var fn = window.location.href.split('/').pop().replace(/[\#\?].*$/,'');
alert(fn);
split('/').pop() removes the path
replace(/[\#\?].*$/,'') replace '#' or '?' until the end $ by empty string
My Javascript ain't so hot, so before I get into some messy string operations, I thought I'd ask:
If the current url is: "http://stackoverflow.com/questions/ask"
What's a good way to to just get: "/questions/ask" ?
Basically I want a string that matches the Url without the domain or the "http://"
alert(window.location.pathname);
Here's some documentation for you for window.location.
ADDITIONAL ANSWER:
window.location.pathname itself is just not enough because it doesn't include the query part, and also URN if exists:
Sample URI = "http://some.domain/path-value?query=string#testURN"
window.location.pathname result = "/path-value"
window.location.search result = "?query=string"
pathname + search result = "/path-value?query=string"
If you want to get all the values just except the domain name, you can use the following code:
window.location.href.replace(window.location.origin, "")
Or as #Maickel suggested, with a simpler syntax:
window.location.href.substring(window.location.origin.length);
This gets the following URL parts correctly:
http://some.domain/path-value?query=string#testURN
alert(window.location.href.replace(window.location.origin, ""))--> "/path-value?query=string#testURN"
Use window.location.pathname.
How would I go about getting the current URL using jquery, or more specifically, getting an ID on the end of it?
For example, I have product.php#tab-2. What I want to get from it is just the '#tab-2' part.
I have tried 'window.location.pathname' but that will only return '/product.php'
Thanks
You don't need jQuery for this:
alert(window.location.href); // will give you the full url
alert(window.location.hash); // will give you the hash (#) value
See the Mozilla docs at window.location - MDC.
You want window.location.hash
Use jqUrl plugin (http://www.oakcitygraphics.com/jquery/jqURL/jqURLdemo.html) to retrieve the full current url, then strip the window.location.pathname part.
Thomas
To actually assign to a variable, use the following;
var url = window.location.href;
var id = url.substring(url.lastIndexOf('#') + 1);
Note that if your url is in this format /product.php/3 , then you can use the above code, just change the character is the lastIndexOf function.