What's the best way to truncate a string to the first n words?
Truncate the string (first argument) if it is longer than the given maximum string length (second argument) and return the truncated string with a ... ending. The inserted three dots at the end should also add to the string length.
About truncation and wildcards Truncation, also called stemming, is a technique that broadens your search to include various word endings and spellings. To use truncation, enter the root of a word and put the truncation symbol at the end. The database will return results that include any ending of that root word.
The other way to truncate a string is to use a rsplit() python function. rsplit() function takes the string, a delimiter value to split the string into parts, and it returns a list of words contained in the string split by the provided delimiter.
You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.
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"]
You could do it like this:
s = "what's the best way to truncate a ruby string to the first n words?" n = 6 trunc = s[/(\S+\s+){#{n}}/].strip
if you don't mind making a copy.
You could also apply Sawa's Improvement (wish I was still a mathematician, that would be a great name for a theorem) by adjusting the whitespace detection:
trunc = s[/(\s*\S+){#{n}}/]
If you have to deal with an n
that is greater than the number of words in s
then you could use this variant:
s[/(\S+(\s+)?){,#{n}}/].strip
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