Javascript regex to find a base URL

前端 未结 2 947
粉色の甜心
粉色の甜心 2021-01-25 17:34

I\'m going mad with this regex in JS:

var patt1=/^http(s)?:\\/\\/[a-z0-9-]+(.[a-z0-9-]+)*?(:[0-9]+)?(\\/)?$/i;

If I give an input string like \

相关标签:
2条回答
  • 2021-01-25 17:56

    I'm no javascript pro, but accustomed to perl regexp, so I'll give it a try; the . in the middle of the regexp might need to be escaped, as it can map a / and jinx the whole regexp.

    Try this way:

    var patt1=/^http(s)?:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*?(:[0-9]+)?(\/)?$/i; 
    
    0 讨论(0)
  • 2021-01-25 18:16

    Considering you have a properly formatted URL this simple RegExp should do the trick every time.

    var patt1=/^https?:\/\/[^\/]+/i;
    

    Here's the breakdown...

    Starting with the first position (denoted by ^)

    Look for http

    http can be followed by s (denoted by the ? which means 0 or 1 of the character or set before it)

    Then look for :// after the http or https (denoted by :\/\/)

    Next match any number of characters except for / (denoted by [^\/]+ - the + means 1 or more)

    Case insensitive (denoted by i)

    NOTE: this will also pick up ports http://example.com:80 - to get rid of the :80 (or a colon followed by any port number) simply add a : to the negated character class [^\/:] for example.

    0 讨论(0)
提交回复
热议问题