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";
Related
I'm trying to make a bookmarklet that will take part of an URL and redirect to the new URL, but I need to change two parts of the URL that are separate.
The base URL could be:
78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png
I need it to end like this:
s3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png
So I need to replace "78.media.tumblr.com" and "1280"
I've tried coming up with something using window.location.assign and location.href.replace but I'm pretty new and couldn't figure it out.
You can do this with regex and window.location.href. This is assuming you are only looking at tumbler though. If you're not, there would be another step in the regex.
// first get the url
var url = window.location.href;
// Use regex to keep only the parts we want and replace the others
var newUrl = url.replace(/.*(\.tumblr.*\_).*(\..*)/, 'http://s3.amazonaws.com/data$1raw$2')
// go to the new page
window.location.href = newUrl;
In general, you can just replace the parts of the string using String.prototype.replace. Depending on how flexible you need the matching to be you can adjust the regexes to be more or less 'matchy'.
const startUrl = '78.media.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_1280.png'
const endUrl = 's3.amazonaws.com/data.tumblr.com/fc87fac5ea0d88e1e22a214d25a169ee/tumblr_p3fjmdiF7f1r9qk1io1_raw.png'
const tumblerRegex = /.*\.tumblr\.com/
const numberRegex = /_\d{4}/
function transform (start) {
return start.replace(tumblerRegex, 's3.amazonaws.com/data.tumblr.com').replace(numberRegex, '_raw')
}
console.log(transform(startUrl) == endUrl)
I have a url https://192.168.1.243/admin/build/take_control. I need to get the string before third occurrence of /, here what I need is https://192.168.1.243.
Assuming that you are always dealing with a URL, and don't want to use regex, you could use the URL.origin.
var url = "https://192.168.1.243/admin/build/take_control";
var base = new URL(url).origin;
console.log(base);
as #Tushar noted, it is important to realise that this is not supported in all browser. (But most of them do).
Try this:
var input = 'https://192.168.1.243/admin/build/take_control';
var output = input.match(/https?:\/\/[^\/]+/)[0]
console.log(output);
it will work if you have http or https at the beginning.
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
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 :-)
Is it possible to create a new Location object in javascript? I have a url as a string and I would like to leverage what javascript already provides to gain access to the different parts of it.
Here's an example of what I'm talking about (I know this doesn't work):
var url = new window.location("http://www.example.com/some/path?name=value#anchor");
var protocol = url.protocol;
var hash = url.hash;
// etc etc
Is anything like this possible or would I essentially have to create this object myself?
Well, you could use an anchor element to extract the url parts, for example:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
var protocol = url.protocol;
var hash = url.hash;
alert('protocol: ' + protocol);
alert('hash: ' + hash);
It works on all modern browsers and even on IE 5.5+.
Check an example here.
How about use the standard URL object?
const url = new URL("http://www.example.com/some/path?name=value#anchor");
const { hash } = url;
Then console.log(hash) will output #anchor.
Warning: This interface is a bit new, so, if you're not using a transpiler, please, check the compatibility table and do your tests at target browsers.
You can leverage the power of an anchor element
var aLink = document.createElement("a");
aLink.href="http://www.example.com/foo/bar.html?q=123#asdf";
alert(aLink.pathname);
You can parse it in a regex to get the parts as matches... I don't have the full code right now, but this can be used to get the querydata:
var myUrl = window.location.href;
var matches = myUrl.match(/([^\?]+)\?(.+)/);
var queryData = matches[2];
matches[0] is the full string, matches(1) is the first part of the URL (up to the ?)... you could build up a regular expression to parse each part of a string url if you want...
You can also use one of the many libraries already out there for this.