JS Location ऑब्जेक्ट
In this page:
location.href;
location.hostname;
location.assign(url);
location.reload();
Location Object क्या है?
window.location currently loaded page के URL को represent करता है और इसके हिस्सों तक read access और कहीं और navigate करने के methods दोनों देता है। यह window.location या छोटे location दोनों के रूप में उपलब्ध है।
उदाहरण: What Is the Location Object?
console.log(location.href); // full URL of the current page
URL के हिस्से पढ़ना
location.href पूरे URL को एक string के रूप में देता है, जबकि location.hostname, location.pathname, और location.search इसे क्रमशः domain, domain के बाद का path, और query string में तोड़ते हैं।
इन्हें अलग-अलग parse करना href string को manually slice करने से कहीं ज़्यादा भरोसेमंद है।
उदाहरण: Reading URL Parts
// Print `location.hostname` to the console
// Print `location.hostname` to the console
console.log(location.hostname);
// Print `location.pathname` to the console
// Print `location.pathname` to the console
console.log(location.pathname);
// Print `location.search` to the console
// Print `location.search` to the console
console.log(location.search);
Programmatically Navigate करना
location.href = 'newpage.html' सेट करना या location.assign('newpage.html') कॉल करना दोनों ही browser को एक नए URL पर navigate करते हैं और उस move को browser history में जोड़ देते हैं, जबकि location.replace() current page को history में छोड़े बिना navigate करता है।
उदाहरण: Navigating Programmatically
// location.href = "newpage.html"; // navigates, adds to history
// location.assign("newpage.html"); // same as above
// location.replace("newpage.html"); // navigates, no history entry
console.log(location.href);
Page को Reload करना
location.reload() current page को ठीक वैसे ही reload करता है जैसे एक manual refresh करता, सभी resources को फिर से fetch करते हुए; modern browsers में अब सिर्फ JavaScript से एक hard cache-bypassing reload को force करने के लिए कोई built-in argument नहीं है।
उदाहरण: Reloading the Page
// location.reload(); // re-fetches all resources, like a manual refresh
console.log("Current page:", location.href);
Query Parameters पढ़ना
location.search '?' से शुरू होने वाली raw query string return करता है, जिसे URLSearchParams API के साथ मिलाकर आप split() और indexOf() से string को hand-parse करने के बजाय individual parameter values साफ तरीके से निकाल सकते हैं।
उदाहरण: Reading Query Parameters
const params = new URLSearchParams(location.search);
console.log(params.get("id")); // reads a query parameter cleanly
location.hrefको assign करना और बाद के code के चलने की उम्मीद करना, जबकि page navigate away होना शुरू कर देता है।location.reload(true)इस्तेमाल करना और forced reload की उम्मीद करना, क्योंकि यह argument deprecated है।- हाथ से
location.searchparse करना,new URLSearchParams(location.search)इस्तेमाल करने के बजाय।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: