Skip to content

Get the URL without any parameters in JavaScript | Example code

  • by

There are multiple ways to Get the URL without any parameters in JavaScript.

First get the get current URL get rid of the query parameters.

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

Second concat origin and pathname, if there’s present a port such as example.com:80, that will be included as well.

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

Get the URL without any parameters in JavaScript

Complete HTML example code:

window location origin + pathname

Using hardcoded URLs for example.

<html>
<body>
	<script>
		var url = new URL("https://www.eyehunts.com/path/?par=1");

		const url_new = url.origin + url.pathname;

		const ulr_orgin = url.origin;

		console.log(url_new);
		console.log(ulr_orgin);
	</script>

</body>
</html>

Output:

Rid of the query parameters using split method

Split the URL till? mark.

<html>
<body>
	<script>
		var url = new URL("https://www.eyehunts.com/path/?par=1");

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

		console.log(url_new);
	</script>

</body>
</html>

Output: https://www.eyehunts.com/path/

Do comment if you have any doubts and suggestion on this JS URL tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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