How to get current url path in javascript?

In javascript, to get the path, you can use:

Ex: https://js-tricks.info/check-path-example

var pathname = window.location.pathname; 
// Returns path only : "check-path-example"
var url = window.location.href;
// Returns full URL : 'https://js-tricks.info/check-path-example'
var origin = window.location.origin;
// Returns base URL : "https://js-tricks.info/check-path-example"

Or jquery, you can use:

$(location).attr('host');
// Returns host
$(location).attr('href');
// Returns href
$(location).attr('protocol');
// Returns protocol

Note:
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

Add a Comment

Your email address will not be published. Required fields are marked *