Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery get root url of website

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.

like image 290
tonco Avatar asked May 02 '14 10:05

tonco


People also ask

How do I find the root URL?

You can determine your server's root URL by browsing to a page on your website and observing the address in the location/address entry field of the browser. The root URL is the section between the colon-slash-slash (://) and the next slash (/), omitting any port number (:portno).

How can I get URL in jQuery?

The current URL in jQuery can be obtained by using the 'href' property of the Location object which contains information about the current URL. The 'href' property returns a string with the full URL of the current page.

How do I get the URL of a Javascript page?

Answer: Use the window. location. href Property location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.


3 Answers

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

like image 71
Per Kristian Avatar answered Sep 23 '22 23:09

Per Kristian


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] 
like image 44
2 revs, 2 users 95% Avatar answered Sep 20 '22 23:09

2 revs, 2 users 95%


slightly shorter:

function getBaseUrl() {
    return window.location.href.match(/^.*\//);
}
like image 43
truefish Avatar answered Sep 23 '22 23:09

truefish