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)
            string c = Input.Substring(MaxLen, 1);
            if (c == " ")
                response = Input.Substring(0, MaxLen);
        } while (MaxLen > 0);

        return response + Trailer;
        return response;



Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s