With PHP

echo urlencode("http://www.image.com/?username=unknown&password=unknown");

Result

http%3A%2F%2Fwww.image.com%2F%3Fusername%3Dunknown%26password%3Dunknown

With Javascript:

var myUrl = "http://www.image.com/?username=unknown&password=unknown";
var encodedURL= "http://www.foobar.com/foo?imageurl=" + encodeURIComponent(myUrl);

DEMO: http://jsfiddle.net/Lpv53/

Answer from Niels on Stack Overflow
🌐
SitePoint
sitepoint.com › blog › javascript › how to get url parameters with javascript
How to Get URL Parameters with JavaScript — SitePoint
November 11, 2024 - Our function assumes the parameters are separated by the & character, as indicated in the W3C specifications. However, the URL parameter format in general is not clearly defined, so you occasionally might see ; or & as separators.
Discussions

Adding a parameter to the URL with JavaScript - Stack Overflow
In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example: Original URL: http://server/myapp.php?id=10 Resulting URL: ... More on stackoverflow.com
🌐 stackoverflow.com
url - How to create query parameters in Javascript? - Stack Overflow
Is there any way to create the query parameters for doing a GET request in JavaScript? Just like in Python you have urllib.urlencode(), which takes in a dictionary (or list of two tuples) and crea... More on stackoverflow.com
🌐 stackoverflow.com
javascript - What is the recommended way to pass urls as url parameters? - Stack Overflow
I ran into this issue, personally I couldn't use any of the accepted answers, but it can also be done by just encoding the url into Base 64, passing it as a parameter, and then decoding it. With javascript, you can encode a string s to base 64 with btoa(s) and decode with atob(s). More on stackoverflow.com
🌐 stackoverflow.com
How do I parse a URL query parameters, in Javascript? - Stack Overflow
Possible Duplicate: Use the get paramater of the url in javascript How can I get query string values in JavaScript? In Javascript, how can I get the parameters of a URL string (not the curren... More on stackoverflow.com
🌐 stackoverflow.com
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › URLSearchParams
URLSearchParams - Web APIs - MDN Web Docs
Search parameters can also be an object. ... const paramsObj = { foo: "bar", baz: "bar" }; const searchParams = new URLSearchParams(paramsObj); console.log(searchParams.toString()); // "foo=bar&baz=bar" console.log(searchParams.has("foo")); // true console.log(searchParams.get("foo")); // "bar"
🌐
Byby
byby.dev › js-parse-url-query-strings
How to parse and format URL query strings in JavaScript
The URLSearchParams API is a native JavaScript API available in modern browsers. It provides methods to parse, modify, and format query strings. You can use it to extract and manipulate individual parameters, add or remove parameters, and stringify ...
🌐
Valentino G.
valentinog.com › blog › url
How to build an URL and its search parameters with JavaScript
February 7, 2020 - Even if myUrlWithParams.searchParams is marked as read-only you can still change the original URL as you wish. Here searchParams is an URLSearchParams object which has an append method for adding new parameters to the search. The URL API is a clean interface for building and validating URLs with JavaScript.
🌐
Medium
medium.com › @AlexanderObregon › using-javascript-url-objects-to-work-with-query-parameters-2d6d5c0cc7b6
Using JavaScript URL Objects to Work with Query Parameters
June 12, 2025 - JavaScript gives you built-in tools for working with URLs and their query parameters without needing to split strings by hand. Modern browsers support the URL and URLSearchParams classes, which handle parsing, updating, and rebuilding URLs using well-defined interfaces. These tools help you avoid messy regular expressions or manual string slicing. They also follow URL standards, so the formatting is consistent and safe to use across projects.
Find elsewhere
🌐
xjavascript
xjavascript.com › blog › how-to-convert-url-parameters-to-a-javascript-object
How to Convert URL Parameters to a JavaScript Object: Step-by-Step Tutorial with Example — xjavascript.com
By converting URL parameters to a JavaScript object, you unlock easier data manipulation and validation in your web apps. Use URLSearchParams for simplicity, and manually parse or use libraries like qs for complex scenarios. Happy coding!
🌐
Medium
medium.com › theleanprogrammer › javascript-encode-url-query-parameter-5cd11aeee4b6
Javascript | Encode URL Query Parameter | by Sonika | @Walmart | Frontend Developer | 11 Years | TheLeanProgrammer | Medium
August 25, 2024 - This means that we need to encode these characters when passing them into a URL. Special characters such as &, space, ! when entered in a URL need to be escaped, otherwise, it may cause unpredictable situations. My Use case: Need to accept query string parameters in order to make GET requests.
🌐
Sentry
sentry.io › sentry answers › javascript › how to get values from urls in javascript
How to get values from URLs in JavaScript | Sentry
You can also use the following methods to loop through the query parameters: ... One thing to note is that the URLSearchParams() constructor interprets plus signs (”+”) as spaces, which can be an issue in certain cases. You can avoid this issue by encoding the URL string using the encodeURIComponent() function.
🌐
Frontend Masters
frontendmasters.com › blog › encoding-and-decoding-urls-in-javascript
Encoding and Decoding URLs in JavaScript – Master.dev Blog
This ensures that any special characters in the URLs are converted into a format that can be safely transmitted over the internet. const dynamicValue = "hello world"; const encodedURL = "https://example.com/search?q=" + encodeURIComponent(dynamicValue); console.log(encodedURL); // Output: "https://example.com/search?q=hello world"Code language: JavaScript (javascript) Handling Form Submissions with URL Parameters: When users submit form data (e.g user profiles), the form data is often included in the URL as query parameters.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-serialize-an-object-into-a-list-of-url-query-parameters-using-javascript
Serialize a JavaScript Object into URL Query Parameters - GeeksforGeeks
January 19, 2026 - // Declare an object let obj = { p1: 'GFG', p2: 'Geeks', p3: 'GeeksForGeeks' }; // Function to serialize an object into // URL query parameters function GFG_Fun() { let s = ""; for (let key in obj) { if (obj.hasOwnProperty(key)) { if (s !== "") { s += "&"; } s += key + "=" + encodeURIComponent(obj[key]); } } console.log("'" + s + "'"); } GFG_Fun(); ... Loops through each property of the object using for...in and processes only its own keys. Appends each key-value pair in key=value format, separating them with &.
🌐
Node.js
nodejs.org › api › url.html
URL | Node.js v26.5.0 Documentation
Parses a string as a URL. If base is provided, it will be used as the base URL for the purpose of resolving non-absolute input URLs. Returns null if the parameters can't be resolved to a valid URL.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › encodeURIComponent
encodeURIComponent() - JavaScript - MDN Web Docs
October 30, 2025 - The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two surrogate characters).
🌐
DEV Community
dev.to › jcmartinezdev › working-with-url-parameters-in-javascript-fi5
Working with URL parameters in JavaScript - DEV Community
January 19, 2023 - Lastly, if we only need all the values, we can use .values(), like with any other iterator object in JavaScript. Besides just retrieving, we can also add, update and delete URL parameters. Adding a new query parameter is done through the append() method, which takes in two arguments: the first one is the key, and the second one is its associated value. const queryString = '?page=5'; const urlParams = new URLSearchParams(queryString); urlParams.append('format', 'json'); console.log(urlParams.toString()); // Outputs: 'page=5&format=json'
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › URLSearchParams › toString
URLSearchParams: toString() method - Web APIs | MDN
February 2, 2025 - Note: This method returns the query string without the question mark. This is different from Location.search, HTMLAnchorElement.search, and URL.search, which all include the question mark. ... A string, without the question mark. Returns an empty string if no search parameters have been set.
Top answer
1 of 2
163

2.5 years after the question was asked you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getSearchOrHashBased(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return "";
  if(hash==-1) hash = url.length;
  return question==-1 || hash==question+1
    ? url.substring(hash)
    : url.substring(question+1, hash);
}

// use query = getSearchOrHashBased(location.href)
// or query = location.search.substring(1)
function getJsonFromUrl(query) {
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.replaceAll("+", " ");
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substring(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substring(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

7 years after the question was asked the functionality was standardized as URLSearchParams and 4 more years after, the access can be further simplified by Proxy as explained in this answer, however that new one can not parse the sample url above.

2 of 2
35

You could get a JavaScript object containing the parameters with something like this:

var regex = /?&=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

🌐
GeeksforGeeks
geeksforgeeks.org › how-to-get-url-parameters-using-javascript
How to get URL Parameters using JavaScript ? | GeeksforGeeks
September 13, 2024 - Creating query parameters in JavaScript involves appending key-value pairs to a URL after the `?` character. This process is essential for passing data to web servers via URLs, enabling dynamic and interactive web applications through GET requests ...