Skip to content

Instantly share code, notes, and snippets.

@haffla
Last active November 3, 2016 12:10
Show Gist options
  • Save haffla/b74e0b8036a2dd3683ad6d99d960f914 to your computer and use it in GitHub Desktop.
Save haffla/b74e0b8036a2dd3683ad6d99d960f914 to your computer and use it in GitHub Desktop.
Truncate only text
def truncateOnlyText t, p
r = %r{<[^<]+>[^<]+</[^<]+>}
h = %r{<[^<]+>}
k = /(?<=>).+(?=<)/
z = []
s = t.gsub(h, '')[0,p]
t.scan(r) do |c|
z << [c, $~.offset(0)[0]]
end
p z
z.take_while{ |m| s.index(m[0].match(k)[0]) }.each do |m|
s.sub!(m[0].match(k)[0], m[0])
end
s
end
p truncateOnlyText "Welcome to the <a href=\"/hotels\">hotel</a> California.", 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment