How to get domain from a string using javascript regular expression

前端 未结 2 1707
离开以前
离开以前 2021-01-03 11:39

As the title suggests, I\'m trying to retrieve the domain from a string using javascript regular expression.

Take the following strings:

String              


        
2条回答
  •  太阳男子
    2021-01-03 12:20

    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"]
    

提交回复
热议问题