Remove “www”, “http://” from string

前端 未结 3 1879
野性不改
野性不改 2021-01-02 01:47

How can I remove \"www\", \"http://\", \"https://\" from strings using Ruby?

I tried this but it didn\'t work:

s.gsub(\'/(?:http?:\\/\\/)?(?:www\\.)?         


        
3条回答
  •  长情又很酷
    2021-01-02 02:27

    This method should catch all 3 variations:

    def strip_url(url)
      url.sub!(/https\:\/\/www./, '') if url.include? "https://www."
    
      url.sub!(/http\:\/\/www./, '')  if url.include? "http://www."
    
      url.sub!(/www./, '')            if url.include? "www."
    
      return url
    end
    
    strip_url("http://www.google.com")
       => "google.com" 
    strip_url("https://www.facebook.com")
       => "facebook.com" 
    strip_url("www.stackoverflow.com")
      => "stackoverflow.com" 
    

提交回复
热议问题