[英]Javascript/jQuery get root url of website
I have website: " http://www.example.com/folder1/mywebsite/subfolder/page.html "我有网站:“ http://www.example.com/folder1/mywebsite/subfolder/page.html ”
Root of the site is: " http://www.example.com/folder1/mywebsite "该站点的根目录是:“ http://www.example.com/folder1/mywebsite ”
I would like to get root url of "mywebsite" dynamicly.我想动态获取“mywebsite”的根网址。 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 "例如:“ http://www.example.com/otherFolder/test/myChangedWebsite/subfolder/page.html ”
I will get: " http://www.example.com/otherFolder/test/myChangedWebsite "我会得到:“ http://www.example.com/otherFolder/test/myChangedWebsite ”
I tried in "page.html" javascript: var url = window.location.protocol + "//" + window.location.host + '/otherPage.html我在 "page.html" javascript: var url = window.location.protocol + "//" + window.location.host + '/otherPage.html 中试过
but this gives me only " http://www.example.com/otherPage.html ".但这只给了我“ 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我也知道 location.origin 但这不是所有浏览器都支持的,因为我在链接上发现了这一点: http : //www.w3schools.com/jsref/prop_loc_origin.asp
If it can be done with jQuery, it will be good as well.如果可以用 jQuery 来完成,那也不错。
Here's a function doing the same as Hawk's post above, only much, much shorter:这是一个功能与上面 Hawk 的帖子相同,只是更短:
function getBaseUrl() {
var re = new RegExp(/^.*\//);
return re.exec(window.location.href);
}
Details here: Javascript: Get base URL or root URL此处的详细信息: Javascript:获取基本 URL 或根 URL
slightly shorter:略短:
function getBaseUrl() {
return window.location.href.match(/^.*\//);
}
if your location is fixed after mywebsite/subfolder/page.html"
如果您的位置在
mywebsite/subfolder/page.html"
之后是固定的mywebsite/subfolder/page.html"
then use this然后用这个
location.href.split("mywebsite")[0]
Use the following javascript to get the root of your url:使用以下 javascript 获取您的 url 的根目录:
window.location.origin
For more details:更多细节:
[https://www.codegrepper.com/code-examples/javascript/javascript+get+root+url][1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.