7

我想知道是否有一种简单的方法可以从字符串中仅获取 N 个符号而不剪切整个单词。

例如,我有产品和产品描述信息。描述长度从 70 到 500 个符号,但我只想显示前 70 个符号,如下所示:

可口可乐是历史上最受欢迎、销量最大的软饮料,也是世界上最知名的品牌。

2011 年 5 月 8 日,可口可乐庆祝成立 125 周年。1886 年,John S. Pemberton 博士在佐治亚州亚特兰大创立了可口可乐,最初是在 Jacob's Pharmacy 将可口可乐糖浆与碳酸水混合而成的喷泉饮料。

所以,普通的子字符串方法会给我:

Coca-Cola is the most popular and biggest-selling soft drink in histor

我需要一种方法来得到这个:

Coca-Cola is the most popular and biggest-selling soft drink in ...
4

6 回答 6

8

只需使用带有分隔符选项的截断:

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..."

获取更多信息:rails API 文档中的 truncate helper

于 2015-01-27T11:05:39.250 回答
5

此方法使用一个正则表达式,它贪婪地抓取多达 70 个字符,然后匹配一个空格或字符串结尾来完成您的目标

def truncate(s, max=70, elided = ' ...')
  s.match( /(.{1,#{max}})(?:\s|\z)/ )[1].tap do |res|
    res << elided unless res.length == s.length
  end    
end

s = "Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world."
truncate(s)
=> "Coca-Cola is the most popular and biggest-selling soft drink in ..."
于 2013-05-06T16:58:52.837 回答
2
s = "Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world."
s = s.split(" ").each_with_object("") {|x,ob| break ob unless (ob.length + " ".length + x.length <= 70);ob << (" " + x)}.strip
#=> "Coca-Cola is the most popular and biggest-selling soft drink in"
于 2013-05-06T11:39:00.867 回答
1
s[0..65].rpartition(" ").first << " ..."

在你的例子中:

s = "Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world."    
t = s[0..65].rpartition(" ").first << " ..."
=> "Coca-Cola is the most popular and biggest-selling soft drink in ..." 
于 2013-05-06T22:32:54.333 回答
0
b="Coca-Cola is the most popular and biggest-selling soft drink in history, as well "

def truncate x
a=x.split("").first(70).join

w=a.split("").map!.with_index do |x,y|
    if x!=" "
        x=nil
    else
        x=y
    end
end
w.compact!
index=w.last

x.split("").first(index).join+" ..."
end

truncate b
于 2017-04-07T21:23:44.910 回答
0

(受 dbenhur 的回答启发,但更好地处理第一个最大字符中没有空格或字符串结尾的情况。)

def truncate(s, options = { })
  options.reverse_merge!({
     max: 70,
     elided: ' ...'
  });

  s =~ /\A(.{1,#{options[:max]}})(?:\s|\z)/
  if $1.nil? then s[0, options[:max]] + options[:elided]
  elsif $1.length != s.length then $1 + options[:elided]
  else $1
  end
end
于 2015-11-03T20:02:19.143 回答