Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get url path without $_GET parameters using javascript?

If my current page is in this format...

http://www.mydomain.com/folder/mypage.php?param=value

Is there an easy way to get this

http://www.mydomain.com/folder/mypage.php

using javascript?

like image 201
Neil Harlow Avatar asked Aug 14 '13 04:08

Neil Harlow


People also ask

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

If you're using JavaScript in the browser you can get the full current URL by using window. location. href .

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.

How do you get the query parameters from the URL in Javascript?

For getting the URL parameters, there are 2 ways: By using the URLSearchParams Object. By using Separating and accessing each parameter pair.

How do I find the URL path in HTML?

window.location.href returns the href (URL) of the current page. window.location.hostname returns the domain name of the web host. window.location.pathname returns the path and filename of the current page.


2 Answers

Don't do this regex and splitting stuff. Use the browser's built-in URL parser.

window.location.origin + window.location.pathname

And if you need to parse a URL that isn't the current page:

var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
console.log(url.origin + url.pathname);

And to support IE (because IE doesn't have location.origin):

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

(Inspiration from https://stackoverflow.com/a/6168370/711902)

like image 55
Trevor Dixon Avatar answered Sep 23 '22 17:09

Trevor Dixon


Try to use split like

var url = "http://www.mydomain.com/folder/mypage.php?param=value";
var url_array = url.split("?");
alert(url_array[0]);    //Alerts http://www.mydomain.com/folder/mypage.php

Even we have many parameters in the GET , the first segment will be the URL without GET parameters.

This is DEMO

like image 42
Gautam3164 Avatar answered Sep 24 '22 17:09

Gautam3164