-
-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathStringExtensions.cs
More file actions
68 lines (57 loc) · 1.53 KB
/
Copy pathStringExtensions.cs
File metadata and controls
68 lines (57 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System.Text;
using System.Text.RegularExpressions;
namespace CounterStrikeSharp.API
{
public static class StringExtensions
{
private const string HTML_TAG_REGEX_PATTERN = "<[^>]+>";
private static readonly Regex TagRegex = new(HTML_TAG_REGEX_PATTERN, RegexOptions.Compiled);
public static string TruncateHtml(this string msg, int maxLength)
{
if (maxLength <= 0)
return msg;
if (string.IsNullOrEmpty(msg))
return string.Empty;
string textOnly = Regex.Replace(msg, HTML_TAG_REGEX_PATTERN, "");
if (textOnly.Length <= maxLength)
return msg;
Stack<string> tagStack = new Stack<string>();
StringBuilder result = new System.Text.StringBuilder();
int visibleLength = 0,
i = 0;
while (i < msg.Length && visibleLength < maxLength)
{
if (msg[i] == '<')
{
Match match = TagRegex.Match(msg, i);
if (match.Success && match.Index == i)
{
string tag = match.Value;
result.Append(tag);
i += tag.Length;
if (!tag.StartsWith("</")) // Opening tag
{
string tagName = tag.Split(new[] { ' ', '>' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim('<');
if (!tag.EndsWith("/>") && !tagName.StartsWith("!"))
tagStack.Push(tagName);
}
else if (tagStack.Count > 0)
{
tagStack.Pop();
}
continue;
}
}
else
{
result.Append(msg[i]);
visibleLength++;
}
i++;
}
while (tagStack.Count > 0)
result.Append($"</{tagStack.Pop()}>");
return result.ToString();
}
}
}