How to get domain from a string using javascript regular expression

时光毁灭记忆、已成空白 提交于 2019-11-30 16:34:25

Use this regex:

/(?:[\w-]+\.)+[\w-]+/

Here is a regex demo!

Sampling:

>>> var regex = /(?:[\w-]+\.)+[\w-]+/
>>> regex.exec("google.com")
... ["google.com"]
>>> regex.exec("www.google.com")
... ["www.google.com"]
>>> regex.exec("ftp://ftp.google.com")
... ["ftp.google.com"]
>>> regex.exec("http://www.google.com")
... ["www.google.com"]
>>> regex.exec("http://www.google.com/")
... ["www.google.com"]
>>> regex.exec("https://www.google.com/")
... ["www.google.com"]
>>> regex.exec("https://www.google.com.sg/")
... ["www.google.com.sg"]

You can use this regex in Javascript:

\b(?:(?:https?|ftp):\/\/)?([^\/\n]+)\/?

RegEx Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!