I am using jQuery. How do I get the path of the current URL and assign it to a variable?
Example URL:
http://localhost/menuname.de?foo=bar&nu
You can log window.location and see all the options, for just the URL use:
window.location.origin
for the whole path use:
window.location.href
there's also location.__
.host
.hostname
.protocol
.pathname
window.location is an object in javascript. it returns following data
window.location.host #returns host
window.location.hostname #returns hostname
window.location.path #return path
window.location.href #returns full current url
window.location.port #returns the port
window.location.protocol #returns the protocol
in jquery you can use
$(location).attr('host'); #returns host
$(location).attr('hostname'); #returns hostname
$(location).attr('path'); #returns path
$(location).attr('href'); #returns href
$(location).attr('port'); #returns port
$(location).attr('protocol'); #returns protocol
Very Commonly Used top 3 ones are
1. window.location.hostname
2. window.location.href
3. window.location.pathname
In pure jQuery style:
$(location).attr('href');
The location object also has other properties, like host, hash, protocol, and pathname.
If there is someone who wants to concatenate the URL and hash tag, combine two functions:
var pathname = window.location.pathname + document.location.hash;
Here is an example to get the current URL using jQuery and JavaScript:
$(document).ready(function() {
//jQuery
$(location).attr('href');
//Pure JavaScript
var pathname = window.location.pathname;
// To show it in an alert window
alert(window.location);
});
$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
//alert(json.message);
});