Javascript regex to find a base URL

前端 未结 2 953
粉色の甜心
粉色の甜心 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题