To remove a query string from a URL in JavaScript:
- Create a
URLobject from the URL string using theURL()constructor. - Set the
searchproperty of theURLobject to an empty string (''). - Get the resulting URL with the
toString()method of theURLobject.
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.
11 Amazing New JavaScript Features in ES13
This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.
