Truncate string with Rails?

前端 未结 7 638
醉酒成梦
醉酒成梦 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:59

    Take a look at truncate, it partially does want you want. If you test whether it got trunctated or not, you could add some of the last part back after the truncated part.

    truncate("Once upon a time in a world far far away")
    # => "Once upon a time in a world..."
    
    truncate("Once upon a time in a world far far away", :length => 17)
    # => "Once upon a ti..."
    
    truncate("Once upon a time in a world far far away", :length => 17, :separator => ' ')
    # => "Once upon a..."
    
    truncate("And they found that many people were sleeping better.", :length => 25, :omission => '... (continued)')
    # => "And they f... (continued)"
    

提交回复
热议问题