I want to know if there an easy way to get only N symbols from string without cutting the whole words.
For example, I have products and products descriptions information. The description length is from 70 to 500 symbols, but I want to display only the first 70 symbols like this:
Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world.
On May 8, 2011, Coca-Cola celebrated its 125thanniversary. Created in 1886 in Atlanta, Georgia, by Dr. John S. Pemberton, Coca-Cola was first offered as a fountain beverage at Jacob's Pharmacy by mixing Coca-Cola syrup with carbonated water.
So, ordinary sub string method will give me:
Coca-Cola is the most popular and biggest-selling soft drink in histor
and I need a method to get only this:
Coca-Cola is the most popular and biggest-selling soft drink in ...
To get the first N words from a string in JavaScript: 1 Call the split method on the string, with an empty space 2 Use the slice method to slice N words 3 Join the results on an empty space More ...
String upToNCharacters = String.format ("%."+ n +"s", str); Awful if n is a variable (so you must construct the format string), but pretty clear if a constant: Interesting alternative, though I can't imagine ever using it, given the more traditional approaches, that were given four years ago.
There are lots of ways to do it, but a regular expression is a useful one line method: This expressions returns the first 11 (any) characters plus any subsequent non-space characters.
What you need to do is to find the first space after the length, then return all the characters up until that point. The proper expression would be: SELECT LEFT (@text + ' ', CHARINDEX (' ', @text, @length)). This guarantees that the query will not fail on shorter strings.
Just use truncate with separator option:
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..."
Get more info at: truncate helper in rails API documentation
This method uses a regexp which greedily grabs up to 70 characters and subsequently matchs a space or end of string to accomplish your goal
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 ..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With