Truncate string with Rails?

前端 未结 7 625
醉酒成梦
醉酒成梦 2021-01-31 07:40

I want to truncate a string as follows:

input:

string = \"abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffddd\"
7条回答
  •  一向
    一向 (楼主)
    2021-01-31 07:54

    Truncate with Custom Omission

    Similar to what some others have suggested here, you can use Rails' #truncate method and use a custom omission that is actually the last part of your string:

    string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffffffd"
    
    truncate(string, length: 37, omission: "...#{string[-5, 5]}")
    # => "abcd asfsa sadfsaf safsdaf aa...ffffffffd"
    

    Exactly what you wanted.

    Bonus Points

    You might want to wrap this up in a custom method called something like truncate_middle that does some fancy footwork for you:

    # Truncate the given string but show the last five characters at the end.
    #
    def truncate_middle( string, options = {} )
      options[:omission] = "...#{string[-5, 5]}"    # Use last 5 chars of string.
    
      truncate( string, options )
    end
    

    And then just call it like so:

    string = "abcd asfsa sadfsaf safsdaf aaaaaaaaaa aaaaaaaaaa ffffdffffdffffdffffffffd"
    
    truncate_middle( string, length: 37 )
    # => "abcd asfsa sadfsaf safsdaf aa...ffffffffd"
    

    Boom!

    Thanks for asking about this. I think it's a useful way to show a snippet of a longer piece of text.

提交回复
热议问题