It’s not always easy to get the URL without parameters JavaScript. This article will go over all of your options and help you find what you are looking for so that you can have a better understanding of how to get this done.
Sometimes, we want to get the URL without query string parameters for different reasons. So you can get it in different ways. Let’s check the code below.
Method 1: By using URL object
I have already discussed in my previous article that how to create URL object. You can follow it. So let’s check how to get only URL using URL Object.
//example url
//http://mywebpage.com/somepage.html?name=john&role=user
//get the current url
var current_url = window.location.href;
//create a new object
var url = new URL(current_url);
console.log(url.href);
So, you will get http://mywebpage.com/somepage.html
.
Method 2: By using split
JavaScript has a split function that takes multiple strings and returns an array of substrings found by splitting the first string into substrings wherever there is a match with any of the other provided strings. I got interested in how to use this function on a large scale since it seemed like it would be useful for processing chunks of text where splitting at every possible character would be too costly. Let’s check the code below:
var url = window.location.href.split('?')[0];
console.log(url);