Truncate string to the first n words

前端 未结 4 1669
有刺的猬
有刺的猬 2020-12-28 14:16

What\'s the best way to truncate a string to the first n words?

4条回答
  •  温柔的废话
    2020-12-28 15:10

    n = 3
    str = "your long    long   input string or whatever"
    str.split[0...n].join(' ')
     => "your long long"
    
    
    str.split[0...n] # note that there are three dots, which excludes n
     => ["your", "long", "long"]
    

提交回复
热议问题