347

I have a URL like http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235.

I want to get the URL without the query string: http://localhost/dms/mduserSecurity/UIL/index.php.

Is there any method for this in JavaScript? Currently I am using document.location.href, but it returns the complete URL.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
saint
  • 3,787
  • 5
  • 19
  • 17
  • 3
    possible duplicate of [Remove querystring from URL](http://stackoverflow.com/questions/2540969/remove-querystring-from-url) – Alex Angas Jan 20 '14 at 05:01

18 Answers18

456

Try this:

let path = window.location.href.split('?')[0]
console.log({path})
Teocci
  • 7,189
  • 1
  • 50
  • 48
tradyblix
  • 7,439
  • 3
  • 25
  • 29
  • 13
    @Lincoln - Why? I see no reason that this would be unsafe. It is also within specs (both the specs for what window.location.href should return and the specs for how URL's work) so it shouldn't have any future problems. It's more easily read and understood for cleaner code. It's shorter for smaller code. And lastly it's less intense and less complicated than Felix's answer. Not saying Felix is wrong, but am saying that without some sort of specific example of failure/insecurity that this answer is superior in pretty much every way. – Jimbo Jonny Sep 22 '12 at 22:16
  • 3
    you should use window.location.pathname ..etc as in other answers – Muayyad Alsadi Aug 21 '13 at 11:43
  • 25
    @JimboJonny @Marcel This doesn't handle fragment identifiers (e.g. the `#` term in http://stackoverflow.com/questions/5817505#5817548). You'd have to use regex or use multiple .split() functions, at which point you've lost the value of this being a "simple" answer at cleansing a URL. Granted this is technically beyond the scope of the question, but I'd say it's still relevant. – andrewb Sep 04 '13 at 01:41
  • 5
    While it is accurate that this does not handle fragment identifiers, the asker did not ask for a completely sanitized URL. He asked specifically for a url with no query string, and this answer delivers exactly that. The same URL, with the query string removed. – Drew Major Mar 15 '18 at 18:46
  • It also loses the fragment identifiers which is not what was asked for. – Utsav Chatterjee Aug 19 '21 at 09:44
414

Read about Window.location and the Location interface:

const urlPieces = [location.protocol, '//', location.host, location.pathname]
let url = urlPieces.join('')

console.log({urlPieces, url})
Teocci
  • 7,189
  • 1
  • 50
  • 48
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 36
    Or if using es6 you can use a string literal ``${location.protocol}//${location.host}${location.pathname}`` – alexreardon Aug 29 '16 at 23:42
  • 3
    Though note that `pathname` may [drop the leading `/` (until IE 11?)](https://developer.mozilla.org/en-US/docs/Web/API/Location#Browser_compatibility). Ah, IE, always a snowflake, ain't ya? – ruffin Jan 28 '20 at 19:29
  • Don't forget location.hash (in some circustances for example in a vuejs project) it would be needed – Giuseppe Apr 07 '21 at 17:03
61
location.toString().replace(location.search, "")
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 21
    This is a very undervalued answer. It's the only one that exactly answers the question. Even shorter option: `location.href.replace(location.search, '')` – Guido Bouman Jun 25 '15 at 08:13
  • 2
    what about there is fragment part e.g. domain.com/?x=1#top – Onur Topal Apr 08 '16 at 05:22
  • 4
    There are 10 answers on this question. Only one of them preserves the hash (*which doesn't exist on the URL the question is asking about anyway*). Why are there two comments pointing out that this answer doesn't preserve the non-existent hash but not any of the others? – Quentin Sep 09 '16 at 13:15
  • This is also the easiest way to decide whether one wants to keep the query string, the hash part, or both. – Francesco Marchetti-Stasi Dec 13 '22 at 11:41
33
var url = window.location.origin + window.location.pathname;
Jason
  • 2,271
  • 2
  • 24
  • 23
18

If you also want to remove hash, try this one: window.location.href.split(/[?#]/)[0]

user1079877
  • 9,008
  • 4
  • 43
  • 54
16

Here's an approach using the URL() interface:

new URL(location.pathname, location.href).href
s4y
  • 50,525
  • 12
  • 70
  • 98
6

To get every part of the URL except for the query:

var url = (location.origin).concat(location.pathname).concat(location.hash);

Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash).

It's better practice to use concat to join Javascript strings together (rather than +): in some situations it avoids problems such as type confusion.

Andrew Faulkner
  • 3,662
  • 3
  • 21
  • 24
6

Try:

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

(NB: .host rather than .hostname so that the port gets included too, if necessary)

Alnitak
  • 334,560
  • 70
  • 407
  • 495
5

just cut the string using split (the easy way):

var myString = "http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235"
var mySplitResult = myString.split("?");
alert(mySplitResult[0]);
pleasedontbelong
  • 19,542
  • 12
  • 53
  • 77
2

How about this: location.href.slice(0, - ((location.search + location.hash).length))

2

Use properties of window.location

var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;

You can see more properties at https://developer.mozilla.org/en/DOM/window.location

detaylor
  • 7,112
  • 1
  • 27
  • 46
1

Here are two methods:

<script type="text/javascript">
    var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
                                =true&pcode=1235";

    var st=s.substring(0, s.indexOf("?"));

    alert(st);

    alert(s.replace(/\?.*/,''));
</script>
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
1

You could make use of the URL constructor like this:

const href = 'http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235'; // document.location.href
const url = new URL(href);
const noSearchUrl = href.replace(url.search, '');
console.log(noSearchUrl);
Tudor Morar
  • 3,720
  • 2
  • 27
  • 25
1

You can create instance of URL and then clear the query string:

const url = new URL(document.location.href);
url.search = '';
console.log(url.href);
0

Just add these two lines to $(document).ready in JS as follow:

$(document).ready(function () {
 $("div.sidebar nav a").removeClass("active");
        $('nav a[href$="'+ window.location.pathname.split("?")[0] +'"]').addClass('active');
});

it is better to use the dollar sign ($) (End with)

$('nav a[href$

instead of (^) (Start with)

$('nav a[href^

because, if you use the (^) sign and you have nested URLs in the navigation menu, (e.g "/account" and "/account/roles")

It will active both of them.

0

window.location.href.split("#")[0].split("?")[0]

BaiJiFeiLong
  • 3,716
  • 1
  • 30
  • 28
0

What I would do in 2023:

const windowUrl = window.location.href;
const { origin, pathname } = new URL(windowUrl);
const urlWithoutQueryOrHash = `${origin}${pathname}`;
Manu Geo
  • 1
  • 2
-1

If you are using navigation bar and want to get the pure url after clicking on the side bar navigation, then the following code might be helpful:

$(document).ready(function () {
    $("div.sidebar nav a").removeClass("active");
    var urlPath = window.location.pathname.split("?")[0];
    var nav = $('div.sidebar nav a').filter(function () {
        return $(this).attr('href').toLowerCase().indexOf(urlPath.toLocaleLowerCase()) > -1;
    });
    $(nav).each(function () {
        if ($(this).attr("href").toLowerCase() == urlPath.toLocaleLowerCase())
            $(this).addClass('active');
    });
});