Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get an object containing parameters of current URL in JavaScript?
JavaScript provides several ways to extract URL parameters from the current page or any URL. This is useful for handling query strings, routing, and dynamic content based on URL parameters.
Using the Location Object
The easiest way to get information about the current URL is to use the Location object. This object is a property of the window object and contains information about the current URL.
<!DOCTYPE html>
<html>
<body>
<script>
// Get the entire URL
var currentURL = window.location.href;
console.log("Full URL:", currentURL);
// Get just the path
var currentPath = window.location.pathname;
console.log("Path:", currentPath);
// Get query string
var queryString = window.location.search;
console.log("Query string:", queryString);
</script>
</body>
</html>
Using URLSearchParams (Modern Approach)
The most modern and efficient way to parse URL parameters is using the URLSearchParams API:
<!DOCTYPE html>
<html>
<body>
<script>
// Example URL with parameters
var url = "https://example.com/page?name=John&age=25&city=NewYork";
// Extract query string
var urlObj = new URL(url);
var params = new URLSearchParams(urlObj.search);
// Create object from parameters
var paramObj = {};
for (let [key, value] of params) {
paramObj[key] = value;
}
console.log("Parameters object:", paramObj);
console.log("Name:", params.get('name'));
console.log("Age:", params.get('age'));
</script>
</body>
</html>
Parameters object: {name: "John", age: "25", city: "NewYork"}
Name: John
Age: 25
Manual Parameter Parsing
For older browser compatibility, you can manually parse URL parameters:
<!DOCTYPE html>
<html>
<body>
<script>
function getUrlParams(url) {
var params = {};
var parser = document.createElement('a');
parser.href = url;
var query = parser.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair.length === 2) {
params[pair[0]] = decodeURIComponent(pair[1]);
}
}
return params;
}
var testUrl = "https://example.com/search?q=javascript&category=tutorials&page=1";
var parameters = getUrlParams(testUrl);
console.log("Parsed parameters:", parameters);
</script>
</body>
</html>
Parsed parameters: {q: "javascript", category: "tutorials", page: "1"}
Interactive Example
Here's a complete example that lets you input any URL and extract its parameters:
<!DOCTYPE html>
<html>
<head>
<title>URL Parameter Extractor</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
input[type="text"] { width: 400px; padding: 8px; }
button { padding: 8px 16px; margin-left: 10px; }
#output { margin-top: 20px; padding: 10px; border: 1px solid #ddd; }
</style>
</head>
<body>
<h1>URL Parameter Extractor</h1>
<p>Enter a URL with parameters to extract them as an object:</p>
<input type="text" id="urlInput" placeholder="https://example.com?param1=value1¶m2=value2"
value="https://tutorialspoint.com/search?q=javascript&category=programming&level=beginner">
<button onclick="extractParams()">Extract Parameters</button>
<div id="output"></div>
<script>
function extractParams() {
var url = document.getElementById('urlInput').value;
var output = document.getElementById('output');
if (!url) {
output.innerHTML = '<p style="color: red;">Please enter a URL</p>';
return;
}
try {
var urlObj = new URL(url);
var params = new URLSearchParams(urlObj.search);
var paramObj = {};
// Convert to regular object
for (let [key, value] of params) {
paramObj[key] = value;
}
// Display results
var html = '<h3>Extracted Parameters:</h3>';
html += '<pre>' + JSON.stringify(paramObj, null, 2) + '</pre>';
if (Object.keys(paramObj).length === 0) {
html += '<p>No parameters found in the URL.</p>';
} else {
html += '<h4>Individual Parameters:</h4>';
for (let key in paramObj) {
html += '<p><strong>' + key + ':</strong> ' + paramObj[key] + '</p>';
}
}
output.innerHTML = html;
} catch (error) {
output.innerHTML = '<p style="color: red;">Invalid URL format</p>';
}
}
// Extract parameters on page load
extractParams();
</script>
</body>
</html>
Comparison of Methods
| Method | Browser Support | Ease of Use | Best For |
|---|---|---|---|
| URLSearchParams | Modern browsers | Very Easy | New projects |
| Manual parsing | All browsers | Moderate | Legacy support |
| Location object | All browsers | Easy | Basic URL info |
Conclusion
Use URLSearchParams for modern applications as it provides the cleanest API for handling URL parameters. For legacy browser support, manual parsing with decodeURIComponent ensures compatibility across all environments.
