Skip to content

Commit 7269f67

Browse files
dkoreckoclaude
andcommitted
feat: add string.Slugify() extension
Generic slug generation was hand-rolled in a consuming project; upstreaming it here so any project can share it instead of duplicating the logic. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent d431989 commit 7269f67

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

‎Devity.Extensions/StringExtensions.cs‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,27 @@
11
using System.Text;
2+
using System.Text.RegularExpressions;
23

34
namespace Devity.Extensions
45
{
56
public static class StringExtensions
67
{
8+
private static readonly Regex NonAlphaNumeric = new("[^a-z0-9]+", RegexOptions.Compiled);
9+
10+
/// <summary>
11+
/// Converts a string into a lowercase slug joined by the given separator (e.g. "Hello World!" with
12+
/// separator '-' becomes "hello-world"). Runs of non-alphanumeric characters collapse to a single
13+
/// separator; leading/trailing separators are trimmed. Returns an empty string for blank input.
14+
/// </summary>
15+
public static string Slugify(this string str, char separator = '-')
16+
{
17+
if (string.IsNullOrWhiteSpace(str))
18+
return string.Empty;
19+
20+
var lowered = str.Trim().ToLowerInvariant();
21+
var collapsed = NonAlphaNumeric.Replace(lowered, separator.ToString());
22+
return collapsed.Trim(separator);
23+
}
24+
725
/// <summary>
826
/// Will shorten the provided string object to the maximum of the provided maximum length. If string is shorter, full string is returned.
927
/// </summary>

0 commit comments

Comments
 (0)