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

前端 未结 3 1862
野性不改
野性不改 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:36

    s = s.sub(/^https?\:\/\//, '').sub(/^www./,'')
    

    If you don't want to use s =, you should use sub!s instead of all subs.

    The problems with your code are:

    1. Question mark always follows AFTER an optional character
    2. Always replace one pattern in a sub. You can "chain up" multiple operations.
    3. Use sub instead of gsub and ^ in the beginning of Regexp so it only replaces the http:// in the beginning but leaves the ones in the middle.

提交回复
热议问题