Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Elegant Way Of Shorten A Text String

DZone's Guide to

Elegant Way Of Shorten A Text String

·
Free Resource
this method shortens a plain text string down to complete words contained in given scope (count)


def shorten (string, count = 30)
	if string.length >= count 
		shortened = string[0, count]
		splitted = shortened.split(/\s/)
		words = splitted.length
		splitted[0, words-1].join(" ") + ' ...'
	else 
		string
	end
end
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}