How to get the URL without any parameters in JavaScript? - javascript

If I use:
alert(window.location.href);
I get everything including query strings. Is there a way to just get the main url part, for example:
http://mysite.com/somedir/somefile/
instead of
http://mysite.com/somedir/somefile/?foo=bar&loo=goo

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("?"));
}

You can concat origin and pathname, if theres present a port such as example.com:80, that will be included as well.
location.origin + location.pathname

Just one more alternative using URL
var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string

Use the URL() constructor, then extract and concatenate the origin and pathname. This will automatically strip the search (aka query) parameters from the url, leaving the scheme, domain, port and pathname only.
const url = new URL('http://localhost:8080/index.html?search=foo&other=bar');
console.log(url.origin + url.pathname);
As a note, this type of transformation is usually referred to as normalization, specifically in this case URI Normalization. There may already exist libraries that accomplish this more robustly with more options in your environment.

var url = "tp://mysite.com/somedir/somefile/?foo=bar&loo=goo"
url.substring(0,url.indexOf("?"));

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

If you look at the documentation you can take just the properties you're interested in from the window object i.e.
protocol + '//' + hostname + pathname

Related

How to trim off the query part of a url using javascript alone?

I've scowerd stackoverflow & for some reason this question is simply not answered in a clear enough manner for me to get right..
I have a url pathname www.thisurl.com/this/url/is/generic%877948
I want to console log the url alone, trimming off the query part of so that all I get is: www.thisurl.com.
I've tried the following:
var pathtotrim = location.href.split('/').pop();
document.write(pathtotrim);
console.log("hello", pathtotrim);
But this trims off the beginning of the url leaving me with /this/url/is/generic%877948.
Essentially doing the opposite of what I want. How can I trim off the query part of a url to be console logged.. please!!!???
Try this:
var pathtotrim = location.href.split('/')[0];
This will split the string on the / but will take the first segment (in your case that would be www.x.com)
Edit:
Like Leilo Faieta Said, location.host or location.hostname would be quicker.
var pathtotrim = "www.thisurl.com/this/url/is/generic%877948".split('/')[0];
document.write(pathtotrim);
console.log("hello", pathtotrim);
let url = 'www.thisurl.com/this/url/is/generic%877948'
console.log(url.replace(/\/.*/g, ''));
There is no need to manipulate strings: you can just use location.host or location.hostname.
This will give you the www part of the url.
on this url:
https://www.google.com/search?safe=off&source=hp&ei=P9SXW7_RO9CKmgWiybjIBA&q=location&oq=location&gs_l=psy-ab.3..0j0i131k1j0l8.269799.273393.0.273746.20.13.4.1.1.0.156.1198.8j4.13.0....0...1c.1.64.psy-ab..2.18.1341.6..35i39k1j0i10k1.98.Zbh8pzpSLkY
you will get
www.google.com
If you want to have all the first part of the url including the http protocol
location.protocol + '//' + location.host
on the same example url you will get
https://www.google.com

How to remove some part of the URL in the address bar of the browser

I try to remove a part of my url in the addressbar of the browser via javascript.
but I don't understand why it's not working, if I test it in the console the result is correct but it still does not change in the address bar.
How can I do it?
url I have:http://localhost:8090/Home/Index?x=72482&success=itsdone
url I want is:
http://localhost:8888/Home/Index?x=72482
here is my javascript code:
window.location.href.replace('&', '#');
window.location.hash = "";
replace doesn't change the string on which you call it (strings are immutable), it returns a new one.
To replace & with #, do
window.location = window.location.href.replace('&', '#');
If you want to remove everything from the first &, the best is to use a regular expression :
window.location = window.location.replace(/&.*$/,'');
If what you want is to retain the x parameter, then you should rebuild the location to ensure it's still OK if the parameters are in a different order in the URL :
window.location = window.location.replace(/([^?]*).*(\?|&)(x=)([^&]+).*/, "$1?$3$4")
This changes
"http://localhost:8888/Home/Index?a=2&x=72482&c=3"
or
"http://localhost:8888/Home/Index?x=72482&success=itsdone"
into
"http://localhost:8888/Home/Index?x=72482"
window.location will cause a page reload. to change the port too use this
window.location = window.location.protocol
+ "//"
+ window.location.host
+ ":8888/"
+ window.location.pathname
+ window.location.search.substr(0, window.location.search.indexOf('&')-1)
Is there a particular reason why you are passing isDone as a QueryString parameter if you do not even need it? Wouldn't it be easier to not even pass it to begin with and have the page decide if you are done?

Remove querystring parameters from url with regex

I'm pretty new to regex and need to remove some content from our url
http://mysite.blah/problem/smtp/smtp-open-relay?page=prob_detail&showlogin=1&action=smtp:134.184.90.18
I need to remove everything from the "?" and on, leaving me just:
http://mysite.blah/problem/smtp/smtp-open-relay
Here is our current regex expression we are using to grab the route data. For example I can grab "smtp" and "smtp-open-relay" (which we need). However sometimes our url changes depending on where the user is coming from thereby appending the querystring parameters which is causing our current regex expression to blow up.
// Retrieve the route data from the route
var routeData = /([0-9a-zA-Z_.-]+)\/([0-9a-zA-Z_.-]+)$/g.exec(route);
I need it to ignore stuff from the "?" on.
A regular expression is probably more than you need.
You could do the following to remove the ? and everything (query
string + hash) after it:
var routeData = route.split("?")[0];
If you truly wanted to strip only the query string, you could preserve
the hash by reconstructing the URL from the window.location object:
var routeData = window.location.origin + window.location.pathname + window.location.hash;
If you want the query string, you can read it with window.location.search.
i just used this one
var routeData= route.substring(0, route.indexOf('?'));
Use this function:
var getCleanUrl = function(url) {
return url.replace(/#.*$/, '').replace(/\?.*$/, '');
};
// get rid of hash and params
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
If you're doing this in-browser, let the browser do the parsing:
location.origin + location.pathname
Or for arbitrary URLs:
function withoutQS(_url) {
var url = document.createElement('a');
url.href = _url;
return url.origin + url.pathname;
}
Following is the cleaner way to remove a given parameter say: prop1 form querystring of url.
Querystring can be found in url by accessing
window.location.search
Here you apply regular expression for prop1:
var queryStringWithoutProp1=window.location.search.replace(/(&?prop1=)(.[^&]*)/,"");
queryStringWithoutProp1 must return querystring without prop1=value parameter-value combination from querystring
Note: '&?' ensures whether prop1 appears as first parameter or any subsequent one.

Remove protocol, domainame, domain and file extension from URL

let say that in our websites we can have urls like:
http://domainame.com/dir/one-simple-name.html
https://dmainame.com/mail/send.php
https://dmainame.com/mail/read
etc..
So i would like to retrieve
dir/one-simple-name
mail/send
mail/read
Whats the best way to achieve it?
Everybody stand back! I know regular expressions!
Try this one:
var my_location = window.location.toString().match(/\/\/[^\/]+\/([^\.]+)/)[1];
I would recommend doing this by,
var url = "https://www.somegoodwebsite.com/happy/ending/results/index.html";
console.log(url.replace(/^.*\/\/[^\/]+/, '') );
;
Result:
happy/ending/results/index.html
You can use this:
var result = window.location.pathname.replace(/\.[^\.\/]+$/, "").substr(1);
In javascript, you can access the various parts of the URL via the window.location object.
window.location.href - the entire URL
window.location.host - the hostname and port number - [www.sample.com]:80
window.location.hostname - the hostname - www.sample.com
window.location.pathname - just the path part - /search
window.location.search - the part of the URL after the ? symbol - ?q=demo
In your case, you can use window.location.pathname and then if you need to strip the file extension off the filename, you can do that with some additional javascript:
var result = window.location.pathname.replace(/\.[^\.\/]+$/, "").substr(1);
This line of javascript will get the pathname component of the URL and then replace any file extension with "" (effectively removing it) and the remove the leading slash.
A more jqueryish way than using just regular expressions:
var path = $('<a>', {href: 'http://google.com/foo/bar.py'})[0].pathname.replace(/\.(.+)$/,'')

How do I trim/strip the URL down to the page name?

How would I go about trimming/stripping the URL down to the page name...
So: http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html
Would become: apage.html
Any ideas?
you do not need jquery:
var url = window.location.href;
var page = url.substring(url.lastIndexOf('/') + 1);
Edit: a good point of the possible query string:
// it might be from browser & / anywhere else
var url = window.location.href;
url = url.split('#').pop().split('?').pop();
var page = url.substring(url.lastIndexOf('/') + 1);
ok, if the location object is available, use pathname gives better result as show below, however, a url can be a string or something directly from text field or span/label. So above solution should have its place.
With location and any link (<a>) elements on the page, you get a load of properties that give you specific parts of the URL: protocol, host, port, pathname, search and hash.
You should always use these properties to extract parts of the URL in preference to hacking about with href and probably getting it wrong for corner cases. For example, every solution posted here so far will fail if a ?query or #fragment is present. The answers from Rob and digitalFresh attempt to cope with them, but will still fail if a / character is present in the query string or fragment (which is valid).
Instead, simply:
var pagename= location.pathname.split('/').pop();
Most of the solutions here are not taking advantage of the window.location object. The location object has this wonderful thing called pathname which returns just the path, no query string, host, protocol, hash, etc.
var mypage = window.location.pathname.split("/").pop();
You could do something like this:
document.location.href.split('/').pop();
Edit: you probably want to get rid of the query string if there is one also:
document.location.href.split('/').pop().split('?').shift();
Edit 2: this will also ignore an anchor in the url if there is one
document.location.href.split('/').pop().split(/\?|#/).shift();
This should also exclude query and hash values.
var path = location.href;
path = path.substring(path.lastIndexOf("/") + 1);
path = path.split("?")[0].split("#")[0];
console.debug(path);
Haven't tested so compeltely guessed, but I'm sure something like this will do :-)
var url = 'http://www.BurtReynoldsMustache.com/whatever/whoever/apage.html';
var page = url.split('/');
alert(page[page.length-1]);​
EDIT Tested under jsfiddle and it was wrong, the above code should now work :-)

Categories