获取URL中的主机名。

huangapple go评论66阅读模式
英文:

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

但更清晰的做法是使用环境变量 获取URL中的主机名。

英文:

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 获取URL中的主机名。

答案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

你可以使用 URLincludes 进行如下操作:

//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) &lt;-- in your website;
const urlDev = new URL(&#39;https://dev.example.com/xx.html&#39;);
const url = new URL(&#39;https://www.example.com/xx.html&#39;);
console.log(url.host.includes(&#39;dev.&#39;), urlDev.host.includes(&#39;dev.&#39;))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月7日 18:45:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定