In javascript, how can I get the relative path of the current url?
for example http://www.example.com/test/this?page=2
I want just the /test/this?page=2
Try
window.location.pathname+window.location.search
location.href
holds the url of the page your script is running in.
The quickest, most complete way:
location.href.replace(/(.+\w\/)(.+)/,"/$2");
location.href.replace(location.origin,'');
Only weird case:
http://foo.com/ >> "/"
You can use the below snippet to get the absolute url of any page.
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
}
})();
// Sample Result based on the input.
getAbsoluteUrl('/'); //Returns http://stackoverflow.com/
Checkout get absolute URL using Javascript for more details and multiple ways to achieve the same functionality.
I use this:
var absURL = document.URL;
alert(absURL);
Reference: http://www.w3schools.com/jsref/prop_doc_url.asp
You should use it the javascript way, to retrieve the complete path including the extensions from the page,
$(location).attr('href');
So, a path like this, can be retrieved too.
www.google.com/results#tab=2
Related
I am trying to get hostname from set of urls that my webapp can encounter with.
The desired output should be something like http://localhost/Webapp/, ending at /Webapp/ and everything after that should be removed.
Kindly note that I dont want to use word Webapp in regex as this name is dynamic and used for demo/testcase only.this can be anything , not harcoded.
In real example I am using location.href.replace(/index.+/g, "").replace(/#.+/g, "")
and I want to keep only hostname ending atWebapp/.
Problem:
my solution seems to working fine except "http://localhost/Webapp/#" is not working correctly ? why is that ? see fiddle below
JSFIDDLE: http://jsfiddle.net/bababalcksheep/um0uqb8v/
JS:
var getHost = function (url) {
return url.replace(/index.+/g, "").replace(/#.+/g, "")
};
var urls = [
"http://localhost/Webapp/",
"http://localhost/Webapp/#",
"http://localhost:8080/Webapp/#sdf#dfgdf#fdg",
"12.168.1.1:8080/Webapp/index.html#",
"https://localhost/Webapp/index.html#ab#bg",
"https://localhost/Webapp/index.html"
];
//Print all urls
$.each(urls, function () {
$("<p/>").text(getHost(this)).appendTo($(".test"));
});
Use url.match(/https?:\/\/([^\/]+)/);
EDIT:
It returns an array where the 1st element is the host with protocol and the 2nd without.
You can try removing anything after the last slash (files and hash-es):
var getHost = function (url) {
return url.replace(/\/[^/]*?$/, '/');
};
And here's the updated fiddle.
There's a bit of a trick you can use to get the browser to extract the hostname for you.
var getHost = function (url) {
var a = document.createElement('a');
a.href = url;
return a.hostname;
};
It also appears you want the path as well. You can access it with the pathname property of the a element. If you're doing that, you ought to rename the function to something like getHostAndPath().
I have website:
"http://www.example.com/folder1/mywebsite/subfolder/page.html"
Root of the site is: "http://www.example.com/folder1/mywebsite"
I would like to get root url of "mywebsite" dynamicly.
If I will publish this site to another place, then I will no need to change script.
For example to: "http://www.example.com/otherFolder/test/myChangedWebsite/subfolder/page.html"
I will get:
"http://www.example.com/otherFolder/test/myChangedWebsite"
I tried in "page.html" javascript:
var url = window.location.protocol + "//" + window.location.host + '/otherPage.html
but this gives me only "http://www.example.com/otherPage.html".
Also I know about location.origin but this is not supported for all browser as I found that on link: http://www.w3schools.com/jsref/prop_loc_origin.asp
If it can be done with jQuery, it will be good as well.
Here's a function doing the same as Hawk's post above, only much, much shorter:
function getBaseUrl() {
var re = new RegExp(/^.*\//);
return re.exec(window.location.href);
}
Details here: Javascript: Get base URL or root URL
Use the following javascript to get the root of your url:
window.location.origin
For more details:
[https://www.codegrepper.com/code-examples/javascript/javascript+get+root+url][1]
slightly shorter:
function getBaseUrl() {
return window.location.href.match(/^.*\//);
}
if your location is fixed after mywebsite/subfolder/page.html"
then use this
location.href.split("mywebsite")[0]
When I visit my url, my script will get the current URL and store it in a variable with
var currentURL = (document.URL);
I'd like to get everything after the forward slash in my url because there will be a hash ID after the forward slash like this:
www.mysite.com/XdAs2
so this is what would be stored in my variable currentURL and I'd like to take only the XdAs2 from it and store that into another variable. In addition, I'd like to know two other things.
Is document.URL the best way to get the current URL or will I have issues with some browsers?
If I were to try to open that URL using an iframe, will document.URL still work? or must there be an address bar present containing the url? I would really appreciate answers for those questions three questions. Thank you
Here's some pseudo code:
var currentURL = (document.URL); // returns http://myplace.com/abcd
var part = currentURL.split("/")[1];
alert(part); // alerts abcd
Basically:
1) document.URL should work fine in all major browsers. For more info refer to this Mozilla Developer Network article or this SO question
2) for an iframe, you need to write something like: document.getElementById("iframe_ID").src.toString()
Using jquery, you can do he following in order to access every inch of the current URL:
www.mysite.com/XdAs2?x=123
assuming you have the following url:
1- get the url in a jQuery object
var currentUrl = $(location)
2- access everything using the following syntax
var result = currentUrl.attr('YOUR_DESIRED_PROPERTY');
some common properties:
hostname => www.mysite.com
pathname => XdAs2
search => ?x=123
I hope this may help.
If you want everything after the host, use window.location.pathname
Following on from Mohammed's answer you can do the same thing in vanilla javascript:
var urlPath = location.pathname,
urlHost = location.hostname;
I know I can get the host name of the current page, by simply doing:
var myhostname = location.hostname;
But how do I get the host name of the referrer? I can get the referrer by
var referrer = document.referrer;
but unfortunately there's no document.referrer.hostname available in JavaScript. How can I get this value?
An example of where this is useful is if somebody clicks a link on google.com. I want to be able to retrieve google.com from the referrer (not the page and the query string).
This would do:
document.referrer.split('/')[2];
Example.
function parseURL(url) {
var a=document.createElement('a');
a.href=url;
return a.hostname;
}
This is a relatively old question, nevertheless this may help any followers.
By parsing it. document.referrer.split( '/' ); will get you close. Or take a look at this
http://blog.stevenlevithan.com/archives/parseuri
If referrer is coming from a browser, it will be sane -- but just in case you want more robust parsing.
You can use var referrer = new URL(document.referrer).hostname.
See https://developer.mozilla.org/en-US/docs/Web/API/URL.URL.
You can use regexp to extract this data.
string.match(/^http([s]?)://([a-zA-Z0-9-_\.]+)(:[0-9]+)?/);
Hi use this function to get domain name.
function getDomain(url) {
if (url) {
var match = /(?:https?:\/\/)?(?:\w+:\/)?[^:?#\/\s]*?([^.\s]+\.(?:[a-z]{2,}|co\.uk|org\.uk|ac\.uk|org\.au|com\.au))(?:[:?#\/]|$)/gi
.exec(url);
return match ? match[1] : null;
} else
return null;
}
It includes the protocol, but document.origin will work. It works via the Origin header, which has no path information included with it.
My problem is that I want to redirect via JavaScript to a directory above.
My code:
location.href = (location.href).substr(0, (location.href).lastIndexOf('folder'))
The URL looks like this:
example.com/path/folder/index.php?file=abc&test=123&lol=cool
The redirect affect just this:
example.com/path/&test=123&lol=cool
But want to have this:
example.com/path/
How can I do it?
You can do a relative redirect:
window.location.href = '../'; //one level up
or
window.location.href = '/path'; //relative to domain
If you use location.hostname you will get your domain.com part. Then location.pathname will give you /path/folder. I would split location.pathname by / and reassemble the URL. But unless you need the querystring, you can just redirect to .. to go a directory above.
https://developer.mozilla.org/en-US/docs/Web/API/Location/assign
window.location.assign("../"); // one level up
window.location.assign("/path"); // relative to domain
redirect to ../
no JS needed
.. means parent directory.
I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:
location.href='/otherSection'
try following js code
location = '..'
This is an old question but just to provide more information, this is how urls work:
window.location.href = 'https://domain/path'; // absolute
window.location.href = '//domain/path'; // relative to current schema
window.location.href = 'path'; // relative to current path
window.location.href = '/path'; // relative to domain
window.location.href = '../'; // one level up