You can use the window.location
object in JavaScript to get the current URL. The location
object has several properties that can be used to get different parts of the URL.
Here are some examples of how to use the location
object to get the current URL:
window.location.href: Returns the entire URL of the current page, including the protocol (http or https), the domain name and the path.
let currentUrl = window.location.href;
console.log(currentUrl); // "http://www.example.com/path/to/page"
window.location.origin: Returns the protocol and the domain name of the current page.
let origin = window.location.origin;
console.log(origin); // "http://www.example.com"
window.location.pathname: Returns the path of the current page.
let pathname = window.location.pathname;
console.log(pathname); // "/path/to/page"
You can also use the location.search
property to get the query parameters of the current page.
let search = window.location.search;
console.log(search); // "?param1=value1¶m2=value2"
It’s worth noting that the location
object is a read-only property, you cannot change the URL of the current page using the location
object.
You can use any of these methods depending on your requirement.
Also Read:
- Difference Between encodeURIComponent() And encodeURI()
- Convert Comma Separated String Into An Array In JavaScript
- How To Check If A String Is Empty In JavaScript
- How To Sort An Array Of Numbers In JavaScript
- How To Return Multiple Values From A Function In JavaScript
- How To Get The Current URL With JavaScript
- How To Include A JavaScript File In Another JavaScript File
- How To Detect Screen Resolution With JavaScript
- How To parse JSON Into JavaScript
- How To Add Elements To An Array In JavaScript
- How To Generate A Timestamp In JavaScript
- How To Convert A JavaScript Object To JSON String
- How To Add An Element To The Beginning Of An Array
- How To Get The Value From The Input Field In JavaScript
- Adjust The iFrame Height To Fit With Content In JavaScript
- Call Two Functions From The Same onClick Event In JavaScript
- How To Detect When A Window Is Resized Using JavaScript
- How To Reset A Form With JavaScript
- How To Pass JavaScript Variables To PHP
- Difference Between PHP And JavaScript
- Armstrong Number In JavaScript
- How To Determine If A Number Is Odd Or Even In JavaScript
- How To Check If A Number Is A Palindrome In JavaScript
- How To Convert Strings To Uppercase In JavaScript
- How To Convert A String To Lowercase In JavaScript
- Code To Check If Age Is Not Less Than 18 Years In JavaScript
- How To Reverse A Number In JavaScript
- How To Check If A Number Is Prime Using JavaScript
- How To Find Factorial Of A Number In JavaScript
- Sum Of Two Numbers In JavaScript
- How To Display The Current Date And Time In JavaScript