Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the URL without any parameters in JavaScript?

Tags:

javascript

People also ask

How do I get the URL of a website using Javascript?

You can simply call the window. location. href property which will return you the complete URL of the webpage including hostname, pathname, and query string. Let's test the JavaScript property practically.

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.


This is possible, but you'll have to build it manually from the location object:

location.protocol + '//' + location.host + location.pathname

Every answer is rather convoluted. Here:

var url = window.location.href.split('?')[0];

Even if a ? isn't present, it'll still return the first argument, which will be your full URL, minus query string.

It's also protocol-agnostic, meaning you could even use it for things like ftp, itunes.etc.


I'm LATE to the party, but I had to solve this recently, figured I'd share the wealth.

const url = window.location.origin + window.location.pathname
//http://example.com/somedir/somefile/

window.location.origin will give you the base url, in our test case: http://example.com

window.location.pathname will give you the route path (after the base url), in our test case /somedir/somefile

SOLUTION 2

You can simply do the following to get rid of the query parameters.

const url = window.location.href.split('?')[0]


Use indexOf

var url = "http://mysite.com/somedir/somefile/?aa";

if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}