How to get a substring of text?

前端 未结 5 1770
无人及你
无人及你 2020-12-02 14:48

I have text with length ~700. How do I get only ~30 of its first characters?

相关标签:
5条回答
  • 2020-12-02 15:38

    Use String#slice, also aliased as [].

    a = "hello there"
    a[1]                   #=> "e"
    a[1,3]                 #=> "ell"
    a[1..3]                #=> "ell"
    a[6..-1]               #=> "there"
    a[-3,2]                #=> "er"
    a[-4..-2]              #=> "her"
    a[12..-1]              #=> nil
    a[-2..-4]              #=> ""
    a[/[aeiou](.)\1/]      #=> "ell"
    a[/[aeiou](.)\1/, 0]   #=> "ell"
    a[/[aeiou](.)\1/, 1]   #=> "l"
    a[/[aeiou](.)\1/, 2]   #=> nil
    a["lo"]                #=> "lo"
    a["bye"]               #=> nil
    
    0 讨论(0)
  • 2020-12-02 15:39

    If you want a string, then the other answers are fine, but if what you're looking for is the first few letters as characters you can access them as a list:

    your_text.chars.take(30)
    
    0 讨论(0)
  • 2020-12-02 15:42

    if you need it in rails you can use first (source code)

    '1234567890'.first(5) # => "12345"
    

    there is also last (source code)

    '1234567890'.last(2) # => "90"
    

    alternatively check from/to (source code):

    "hello".from(1).to(-2) # => "ell"
    
    0 讨论(0)
  • 2020-12-02 15:43

    Since you tagged it Rails, you can use truncate:

    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-truncate

    Example:

     truncate(@text, :length => 17)
    

    Excerpt is nice to know too, it lets you display an excerpt of a text Like so:

     excerpt('This is an example', 'an', :radius => 5)
     # => ...s is an exam...
    

    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-excerpt

    0 讨论(0)
  • 2020-12-02 15:44

    If you have your text in your_text variable, you can use:

    your_text[0..29]
    
    0 讨论(0)
提交回复
热议问题