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
All browsers support Javascript window object. It defines the window of the browser.
The global objects and functions become part of the window object automatically.
All global variables are window objects properties and all global functions are its methods.
The whole HTML document is a window property too.
So you can use window.location object to get all url related attributes.
Javascript
console.log(window.location.host); //returns host
console.log(window.location.hostname); //returns hostname
console.log(window.location.pathname); //return path
console.log(window.location.href); //returns full current url
console.log(window.location.port); //returns the port
console.log(window.location.protocol) //returns the protocol
JQuery
console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname'));
console.log("href = "+$(location).attr('href'));
console.log("port = "+$(location).attr('port'));
console.log("protocol = "+$(location).attr('protocol'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
For the host name only, use:
window.location.hostname
The following are examples of useful code snippets that can be used – some of the examples use standard JavaScript functions and are not specific to jQuery:
See 8 Useful jQuery Snippets For URL’s & Querystrings.
To get the URL of the parent window from within an iframe:
$(window.parent.location).attr('href');
NB: only works on same domain
window.location will give you the current URL, and you can extract whatever you want from it...
This is a more complicated issue than many may think. Several browsers support built-in JavaScript location objects and associated parameters/methods accessible through window.location
or document.location
. However, different flavors of Internet Explorer (6,7) don't support these methods in the same way, (window.location.href
? window.location.replace()
not supported) so you have to access them differently by writing conditional code all the time to hand-hold Internet Explorer.
So, if you have jQuery available and loaded, you might as well use jQuery (location), as the others mentioned because it resolves these issues. If however, you are doing-for an example-some client-side geolocation redirection via JavaScript (that is, using Google Maps API and location object methods), then you may not want to load the entire jQuery library and write your conditional code that checks every version of Internet Explorer/Firefox/etc.
Internet Explorer makes the front-end coding cat unhappy, but jQuery is a plate of milk.