URL Manipulation and URLSearchParams Object in JavaScript

URL Manipulation and URLSearchParams Object in JavaScript

I. URL Manipulation Fundamentals
The URL (Uniform Resource Locator) is a core concept in web development for handling resource addresses. JavaScript provides the URL constructor for parsing and manipulating URLs.

// Create a URL object
const url = new URL('https://example.com:8080/path?name=john&age=25#section');

// Deconstruct URL parts
console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com" 
console.log(url.port);     // "8080"
console.log(url.pathname); // "/path"
console.log(url.search);   // "?name=john&age=25"
console.log(url.hash);     // "#section"

II. URLSearchParams Object in Detail
URLSearchParams is specifically designed for handling URL query strings (the part after ?), providing more convenient manipulation methods.

  1. Creating URLSearchParams Instances
// Method 1: From a string
const params1 = new URLSearchParams('name=john&age=25');

// Method 2: From an array of key-value pairs
const params2 = new URLSearchParams([
  ['name', 'john'],
  ['age', '25']
]);

// Method 3: From an object (requires conversion)
const params3 = new URLSearchParams({name: 'john', age: '25'});
  1. Basic Manipulation Methods
const params = new URLSearchParams('name=john&age=25&skill=js');

// Query operations
console.log(params.get('name'));    // "john"
console.log(params.has('age'));     // true
console.log(params.getAll('skill')); // ["js"]

// Add/Modify operations
params.set('country', 'US');        // Add a new parameter
params.set('name', 'alice');        // Modify an existing parameter
params.append('skill', 'python');   // Append a duplicate parameter value

// Delete operation
params.delete('age');               // Delete a specified parameter

III. Practical Application Scenarios

  1. Dynamically Constructing URLs
function buildURL(baseURL, queryParams) {
  const url = new URL(baseURL);
  const params = new URLSearchParams(queryParams);
  
  url.search = params.toString();
  return url.href;
}

const result = buildURL('https://api.example.com/data', {
  page: 1,
  limit: 10,
  search: 'javascript'
});
// Result: "https://api.example.com/data?page=1&limit=10&search=javascript"
  1. Parsing Current Page URL Parameters
// Get the current page's query parameters
const currentParams = new URLSearchParams(window.location.search);

// Safely get a parameter value (with a default)
function getQueryParam(key, defaultValue = '') {
  const params = new URLSearchParams(window.location.search);
  return params.get(key) || defaultValue;
}

const page = getQueryParam('page', '1');
const search = getQueryParam('search', '');

IV. Advanced Features and Considerations

  1. Parameter Encoding Handling
    URLSearchParams automatically handles encoding and decoding of special characters:
const params = new URLSearchParams();
params.set('query', 'hello world&special=chars');

console.log(params.toString()); 
// "query=hello+world%26special%3Dchars" (automatically encoded)

const decoded = new URLSearchParams('query=hello+world%26special%3Dchars');
console.log(decoded.get('query')); 
// "hello world&special=chars" (automatically decoded)
  1. Iteration Operations
const params = new URLSearchParams('name=john&age=25&skill=js');

// Iterate using for...of
for (const [key, value] of params) {
  console.log(`${key}: ${value}`);
}

// Convert to a regular object
const paramsObj = Object.fromEntries(params);
console.log(paramsObj); // {name: "john", age: "25", skill: "js"}
  1. Using in Combination with the URL Object
// Modify parameters of an existing URL
const url = new URL('https://example.com/page?old=value');
url.searchParams.set('newParam', 'newValue');
url.searchParams.delete('old');

console.log(url.href); 
// "https://example.com/page?newParam=newValue"

V. Compatibility and Polyfill

  • Modern browsers fully support URL and URLSearchParams.
  • For older browser support, polyfills like whatwg-url can be used.
  • Node.js has native support starting from version 7.

This method is safer and more reliable than traditional string manipulation, avoiding errors from manual encoding handling.