英文:
How do i get the host name from a URL in my case?
问题
我试图实现的是从URL获取主机名并确定环境类型。
现在我有两个需要确定的网站。
这是一个网站
https://dev.example.com/xx.html
另一个网站是
https://www.example.com/xx.html
我只需要在开头如果有"dev"则将变量设置为true,否则设置为false。
我该如何继续并确定哪个是开发环境,哪个不是?
英文:
what I am trying to achieve is get the host name from a URL and determine which type of environment.
Right now i have two websites which I need to determine.
This is one website
https://dev.example.com/xx.html
The other web site is
https://www.example.com/xx.html
all i need is to make a variable true if dev is present in the start or else false
How do i proceed and determine which is dev and which is not dev website
答案1
得分: 1
你可以查看 window.location
属性:https://developer.mozilla.org/en-US/docs/Web/API/Location/hostname
但更清晰的做法是使用环境变量
英文:
You should take a look to window.location
properties : https://developer.mozilla.org/en-US/docs/Web/API/Location/hostname
But the clean way to do that is to use ENV variables
答案2
得分: 1
只返回翻译好的部分:
// 在构建阶段标记应用程序版本被认为是一种良好的实践,但是,这里是一个示例
const parser = document.createElement('a');
parser.href = window.location.href;
const hostname = parser.hostname;
// 检查主机名是否以"dev."开头
const isDev = hostname.startsWith("dev.");
isDev ? console.log("这是一个开发网站。") : console.log("这不是一个开发网站。");
英文:
It is considered good practice to mark the version of an application at the build stage, but yeah, here an example
const parser = document.createElement('a');
parser.href = window.location.href;
const hostname = parser.hostname;
// Check if the hostname starts with "dev."
const isDev = hostname.startsWith("dev.");
isDev ? console.log("This is a dev website.") : console.log("This is not a dev website.");
答案3
得分: 1
//const url = new URL(window.location) <-- 在你的网站中;
const urlDev = new URL('https://dev.example.com/xx.html');
const url = new URL('https://www.example.com/xx.html');
console.log(url.host.includes('dev.'), urlDev.host.includes('dev.'))
请注意,上述代码是使用 URL 和 includes 方法的 JavaScript 示例。
英文:
You can use URL with includes like:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
//const url = new URL(window.location) <-- in your website;
const urlDev = new URL('https://dev.example.com/xx.html');
const url = new URL('https://www.example.com/xx.html');
console.log(url.host.includes('dev.'), urlDev.host.includes('dev.'))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论