360

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.

1

18 Answers 18

471

Try this:

let path = window.location.href.split('?')[0]
console.log({path})

Sign up to request clarification or add additional context in comments.

5 Comments

@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.
you should use window.location.pathname ..etc as in other answers
@JimboJonny @Marcel This doesn't handle fragment identifiers (e.g. the # term in 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.
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.
It also loses the fragment identifiers which is not what was asked for.
415

Read about Window.location and the Location interface:

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

console.log({urlPieces, url})

3 Comments

Or if using es6 you can use a string literal ${location.protocol}//${location.host}${location.pathname}
Though note that pathname may drop the leading / (until IE 11?). Ah, IE, always a snowflake, ain't ya?
Don't forget location.hash (in some circustances for example in a vuejs project) it would be needed
67
location.toString().replace(location.search, "")

4 Comments

This is a very undervalued answer. It's the only one that exactly answers the question. Even shorter option: location.href.replace(location.search, '')
what about there is fragment part e.g. domain.com/?x=1#top
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?
This is also the easiest way to decide whether one wants to keep the query string, the hash part, or both.
36
var url = window.location.origin + window.location.pathname;

4 Comments

down-voted because origin is not supported in IE11 :-(
Why would you down-vote something just because it doesn't work in a particular browser? A lot of places still use IE10 as a standard because of applications that they use.
Works in IE11.309.16299.0
This is the best answer in 2022.
19

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

Comments

17

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

new URL(location.pathname, location.href).href

Comments

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)

Comments

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]);

Comments

5

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.

Comments

4

What I would do in 2023:

const windowUrl = window.location.href;
const { origin, pathname } = new URL(windowUrl);
const urlWithoutQueryOrHash = `${origin}${pathname}`;

Comments

3

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);

Comments

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

Comments

2

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

Comments

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>

Comments

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);

Comments

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.

Comments

0

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

Comments

-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');
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.