you could write your own extension method to achieve this.
Following is just an idea and untested:
public static string TruncateByWords(this string text, int maxWords, string suffix = "...")
{
int spaceCount = 0;
string result = null;
text = text.Trim();
foreach (var character in text.ToCharArray())
{
if (character == ' ')
{
spaceCount++;
if (spaceCount == maxWords)
{
result += suffix;
break;
}
}
result += character;
}
return result;
}
Thanks for of the solutions. Ideally I would need a merge of both :-) As Jonathan, your solution is closer to what I need, but the result shows the html tags as well. Not sure how to fix that.
Dave, your solution displays HTML formatted text, so that's great, but the words get cut off.
How to trancate by words in mvc using Umbraco 8?
Hi,
I'd like to truncate my text to 20 words with elipsis at the end, could anybody advise me what method to use in umbraco 8?
Thanks!
Hi
I don't think there is anything in Umbraco to truncate by number of words, but there is by number of characters.
and that returns
lorem ipsum dolor si…
Cheers
Paul
Hi kometa,
you could write your own extension method to achieve this. Following is just an idea and untested:
And use it like this:
~Jonathan
Thanks for of the solutions. Ideally I would need a merge of both :-) As Jonathan, your solution is closer to what I need, but the result shows the html tags as well. Not sure how to fix that.
Dave, your solution displays HTML formatted text, so that's great, but the words get cut off.
Thanks.
Hi kometa,
you should be able to do the following to avoid html:
~ Jonathan
That unfortunately didn't work.
However, I found that this does exactly what I need :-)
@Html.TruncateByWords(item.Value("longText").ToString(), 20, true);
Thank you for your help.
is working on a reply...