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(/\.(.+)$/,'')
Related
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
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?
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
I have:
var uri = window.location.href;
That provides http://example.com/something#hash
What's the best and easiest way to get the entire path without the #hash?
uri = http://example.com/something#hash
nohash = http://example.com/something
I tried using location.origin+location.pathname which doesn't work in every browser. I tried using location.protocol+'//'+location.host+location.pathname which looks like kind of a crappy solution to me.
What is the best and easiest way to do so? maybe I query for location.hash and try to substr() this from the uri?
location.protocol+'//'+location.host+location.pathname is the correct syntax if you do not care about port number or querystring
If you do care:
https://developer.mozilla.org/en/DOM/window.location
location.protocol+'//'+
location.host+
location.pathname+
(location.search?location.search:"")
or
location.protocol+'//'+
location.hostname+
(location.port?":"+location.port:"")+
location.pathname+
(location.search?location.search:"")
You can also just do a location.href.replace(location.hash,"")
It will remove EVERYTHING from the FIRST # and on regardless of other hash characters in the string
Alternatively create a URL object:
const url = new URL("https://www.somepage.com/page.hmtl#anchor") //(location.href);
console.log(url)
url.hash="";
console.log(url)
var uri = window.location.href.split("#")[0];
// Returns http://example.com/something
var hash = window.location.hash;
// Returns #hash
location.href.replace(location.hash,"")
Is the universal way also the smaller?
location.href.split(/\?|#/)[0]
Shorter solutions:
without query string and hash location.href.split(location.search||location.hash||/[?#]/)[0]
only without hash location.href.split(location.hash||"#")[0]
(I usually use the first one)
ES2020:
let [uri, hash] = location.href.split("#");
console.log(uri, hash);
location.hash = "#myhash";
[uri, hash] = location.href.split("#");
console.log(uri, hash);
I was looking for this answer:
`${window.location.origin}${window.location.pathname}${window.location.search}`
location.href = window.location.href.split("write here your code to delete in your URL")[0] + "write here your final destination";
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 :-)