Categories
JavaScript Answers

How to Remove the Query String from URL with JavaScript?

Spread the love

Sometimes, we want to remove the query string part of a URL with JavaScript.

In this article, we’ll look at how to remove the query string part of a URL string with JavaScript.

Use the String.prototype.split Method

We can use the JavaScript string split method to remove the query string from the URL string.

For instance, we can write:

const getPathFromUrl = (url) => {
  return url.split("?")[0];
}
const testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
console.log(getPathFromUrl(testURL))

to create the getPathFromUrl function that returns the part of the URL before the query string.

The query string always follows the question mark, so we can use split with any URL.

We call split on the url with '?' as the separator with [0] to get the part before the query string.

Therefore, in the console log, we see '/Products/List’ is logged.

Use the String.prototype.replace Method

Another way to remove the query string from the URL is to use the JavaScript string replace method.

For instance, we can write:

const getPathFromUrl = (url) => {
  return url.replace(/(?.*)|(#.*)/g, "")
}
const testURL = '/Products/List?SortDirection=dsc&Sort=price&Page=3&Page2=3&SortOrder=dsc'
console.log(getPathFromUrl(testURL))

We call replace with a regex to remove the part of the URL after the ? and also the part after the # sign with an empty string.

And so, we get the same result as we did in the previous example.

Conclusion

We can remove the query string part of a URL string in JavaScript with some string methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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