How to refer to main domain without hard-coding its name?

后端 未结 4 2018
半阙折子戏
半阙折子戏 2021-02-19 22:01

I have a domain name: TestSite.com. I create several subdomains for this site and refer to them as first.TestSite.com, second.TestSite.com, etc.

How do I refer to TestSi

4条回答
  •  佛祖请我去吃肉
    2021-02-19 22:18

    There's no way using pure relative links. You have to program it as a string manipulation.

    Something like:

    var host = location.host;
    var lastPeriod = host.lastIndexOf(".");
    var remainder = host.substring(0, lastPeriod);
    var afterSecondLastPeriod = remainder.lastIndexOf('.') + 1
    var baseDomain = host.substring(afterSecondLastPeriod);
    console.log(baseDomain);
    

    EDIT: Shorter version using regex:

    var baseDomain = host.match(/[^.]*\.[^.]*$/)[0]
    

    This is general, so it will always return the last part. Regardless of whether it's a.TestSite.com, b.a.TestSite.com, etc. it will return TestSite.com.

    You will have to modify it if this assumption is not correct.

提交回复
热议问题