Truncate HTML formatted text without cutting words

Missing all those words because the simply Trucate method is cutting the words? This Truncate method will rip off all HTML syntax and won’t cut the word in half.

/// <summary>
/// Truncate plain text string without cutting words appending <see cref="trailer"/> to it
/// </summary>
public static string Special(string Input, int MaxLen, string Trailer)
{
    if (Input == null)
        throw new ArgumentNullException();

    Input = Input.Trim();

    if (string.IsNullOrEmpty(Input))
        return Input;

    string response = "";

    Regex tags = new Regex("<(.|\n)+?>");
    if (tags.IsMatch(Input))
    {
        Input = tags.Replace(Input, "");
    }

    response = Input;

    if (Input.Length > MaxLen)
    {
        do
        {
            string c = Input.Substring(MaxLen, 1);
            if (c == " ")
            {
                response = Input.Substring(0, MaxLen);
                break;
            }
            MaxLen--;
        } while (MaxLen > 0);

        return response + Trailer;
    }
    else
    {
        return response;
    }

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s