21

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.

4 Answers 4

34

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

Sign up to request clarification or add additional context in comments.

1 Comment

In MVC application, it gives http://locahhost/sitename/controllername instead of http://locahhost/sitename
10

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]

1 Comment

This should be accepted answer
4

slightly shorter:

function getBaseUrl() {
    return window.location.href.match(/^.*\//);
}

Comments

0

if your location is fixed after mywebsite/subfolder/page.html"

then use this

location.href.split("mywebsite")[0]

1 Comment

For this I need to every time specified name of "mywebsite" - example from @Hawk solved my problem, but thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.