【问题标题】:How to get only hostname from the url using javascript regex?如何使用 javascript 正则表达式从 url 中仅获取主机名?
【发布时间】:2019-09-23 22:00:21
【问题描述】:

我有以下网址

1) https://stackoverflow.com/questions/ask?guided=true
2) https://www.youtube.com/watch?v=ClkQA2Lb_iE
3) https://trello.com/b

我只需要从上面的 url 中获取主机名。 所以输出应该是

1) stackoverflow
2) youtube
3) trello

【问题讨论】:

标签: javascript regex string url


【解决方案1】:

使用模式/(\w+)\.\w{2,}(\/|\?|$)/ 从 url 获取域名。正则表达式匹配任何在/? 之前的字符串

var getName = function(url){
  return url.match(/(\w+)\.\w{2,}(\/|\?|$)/)[1];
}

console.log(
  getName("https://stackoverflow.com/questions/ask?guided=true"),
  getName("https://www.youtube.com/watch?v=ClkQA2Lb_iE"),
  getName("https://trello.com")
) 

【讨论】:

  • 这个https://www.google.co.in/你好,我只收到co...你能检查一下吗
  • @Profer 你说得对。这是因为没有正确的解决方案来使用正则表达式或解析器检测域名。即使是解析 url 的 javascript URL 对象也将 google.co.in 作为 hostname 返回并且不返回 google。我认为您有完成这项工作的域后缀列表。
  • 所以不可能?我必须采取完整的网址google.co.in
  • @Profer 我找不到任何解决方案,您只能获取包含域后缀的主机名
猜你喜欢
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 2011-05-31
  • 2013-01-31
  • 2012-07-18
  • 2016-04-21
  • 1970-01-01
  • 2017-05-25
相关资源
最近更新 更多