Add http(s) to URL if it's not there?

前端 未结 7 1939
抹茶落季
抹茶落季 2020-12-08 19:27

I\'m using this regex in my model to validate an URL submitted by the user. I don\'t want to force the user to type the http part, but would like to add it myself if it\'s n

7条回答
  •  無奈伤痛
    2020-12-08 19:49

    Don't do this with a regex, use URI.parse to pull it apart and then see if there is a scheme on the URL:

    u = URI.parse('/pancakes')
    if(!u.scheme)
      # prepend http:// and try again
    elsif(%w{http https}.include?(u.scheme))
      # you're okay
    else
      # you've been give some other kind of
      # URL and might want to complain about it
    end
    

    Using the URI library for this also makes it easy to clean up any stray nonsense (such as userinfo) that someone might try to put into a URL.

提交回复
热议问题