【问题标题】:How to get the hostname of a url in react jsreactjs如何获取url的主机名
【发布时间】:2021-08-27 23:22:57
【问题描述】:

我正在尝试传入一个 url 并在 react 中获取这样的主机名:

const url = "https://www.stackoverflow.com/questions/ask";

hostname = baseurl(url);
console.log(hostname);

输出:

stackoverflow

我将如何创建这个函数?

【问题讨论】:

  • 查看new URL(..)

标签: javascript reactjs function url


【解决方案1】:

有一个URL() 函数可以为您执行此操作。

let url = new URL('https://stackoverflow.com/admin');
alert(url.host);

【讨论】:

  • 这在我直接为 url 传入字符串时有效,但是当我使用 const 时会抛出此错误:TypeError: Failed to construction 'URL': Invalid URL, 即使它是确切的相同的网址,相同的格式,相同的一切。
  • 它对我来说很好用,不知道你要去哪里。如果我声明一个const link = 'https://stackoverflow.com/admin',然后执行let url = new URL(link),然后是console.log(url.host),我会得到相同的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2012-03-26
  • 2019-09-14
  • 2012-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多