How to Remove a Query String From a URL in JavaScript

To remove a query string from a URL in JavaScript:

  1. Create a URL object from the URL string using the URL() constructor.
  2. Set the search property of the URL object to an empty string ('').
  3. Get the resulting URL with the toString() method of the URL object.
const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

urlObj.search = '';

const result = urlObj.toString();

console.log(result); // https://example.com/posts#hash

We can use the URL class to parse, construct, normalize, and encode URLs.

The URL() constructor returns a newly created URL object representing the URL string passed as an argument. URL objects have properties that allow us to easily read and modify the components of a URL.

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

console.log(urlObj.host); // example.com

console.log(urlObj.origin); // https://example.com

console.log(urlObj.protocol); // https:

The search property returns the query string of the URL, including the ? character. It doesn’t include the hash.

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

console.log(urlObj.search); // ?page=5&sort=desc

By setting search to an empty string (''), we remove the query string from the URL.

Remove query string along with hash from URL

To remove the hash of the URL along with the query string, also set the hash property to an empty string:

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

urlObj.search = '';
urlObj.hash = '';

const result = urlObj.toString();

console.log(result); // https://example.com/posts

The hash property returns the fragment identifier of the URL, including the # character.

const url = 'https://example.com/posts?page=5&sort=desc#hash';

const urlObj = new URL(url);

console.log(urlObj.hash); // #hash

By setting hash to an empty string (''), we remove the hash from the URL along with the query string.



Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *