Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • kometa 23 posts 76 karma points
    Sep 25, 2019 @ 15:55
    kometa
    0

    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!

  • Paul Seal 524 posts 2889 karma points MVP 6x c-trib
    Sep 25, 2019 @ 21:36
    Paul Seal
    0

    Hi

    I don't think there is anything in Umbraco to truncate by number of words, but there is by number of characters.

    @{
        var htmlStringUtilities = new HtmlStringUtilities();
    }
    <p>@htmlStringUtilities.Truncate("lorem ipsum dolor sit amet", 20, true, false)</p>
    

    and that returns lorem ipsum dolor si…

    Cheers

    Paul

  • Jonathan Distenfeld 105 posts 618 karma points
    Sep 26, 2019 @ 07:26
    Jonathan Distenfeld
    0

    Hi kometa,

    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;
    }
    

    And use it like this:

    Model.Value<string>("someProperty").TruncateByWords(20);
    

    ~Jonathan

  • kometa 23 posts 76 karma points
    Sep 26, 2019 @ 08:01
    kometa
    0

    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.

  • Jonathan Distenfeld 105 posts 618 karma points
    Sep 26, 2019 @ 08:08
    Jonathan Distenfeld
    0

    Hi kometa,

    you should be able to do the following to avoid html:

    Html.Raw(Model.Value<string>("someProperty")).ToString().TruncateByWords(20);
    

    ~ Jonathan

  • kometa 23 posts 76 karma points
    Sep 26, 2019 @ 08:18
    kometa
    103

    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.

Please Sign in or register to post replies

Write your reply to:

Draft