Trimming or truncating text to a character limit involves shortening a string to a specific length. This is useful for various purposes, like displaying text previews or summaries, fitting text within UI elements, or adhering to character limits on platforms like social media.
To trim text to a character limit without breaking words in Kentico, you can cut the string at the limit and then backtrack to the last full word by finding the last space.
Here’s how the logic works:
Substring(0, charLimit) – Trims to max length.
LastIndexOf(‘ ‘) – Finds the last whole word boundary.
And last, it adds “…” after a clean trim.
On your Properties page make sure you declare the string variable (SummaryChars) that holds the number of characters:
[TextInputComponent(Label = "Summary Text Limit", Order = 1, ExplanationText = "Limit number of characters. Default: 200")]
public string SummaryChars { get; set; } = "200";
On your Component page convert SummaryChars from string to int:
int summaryCharLimit = 200;
if (!string.IsNullOrWhiteSpace(properties.SummaryChars) &&
int.TryParse(properties.SummaryChars, out int parsedValue))
{
summaryCharLimit = Math.Clamp(parsedValue, 1, 500);
}
In your Helpers folder, create a new Helper class called TrimTextHelper.cs that strips the HTML code and handles punctuation gracefully.
using System.Text.RegularExpressions;
namespace YourNamespace.Helpers
{
public static class TrimTextHelper
{
public static string StripHtml(string input)
{
return Regex.Replace(input ?? "", "<.*?>", string.Empty);
}
public static string TrimToWord(string input, int limit)
{
string clean = StripHtml(input);
if (string.IsNullOrWhiteSpace(clean) || clean.Length <= limit)
return clean;
string cut = clean.Substring(0, limit);
int lastSpace = cut.LastIndexOf(' ');
return lastSpace > 0 ? cut.Substring(0, lastSpace) + "..." : cut + "...";
}
}
}
On your Razor page display the trimmed description:
@using YourNamespace.Helpers @TrimTextHelper.TrimToWord(Model.PageDescription, Model.SummaryChars)