I think your method is pretty readable and clean as it stands. However, if you want to simplify the method itself, I have a decent support structure that would do so and possibly speed it up for particularly long strings:
internal static partial class SafeTag
{
private static readonly IEnumerable<Replacement> _Replacements =
[
new Replacement("'", "`"),
new Replacement("\"", "`"),
new Replacement("&", "and"),
new Replacement(",", ":"),
new Replacement("\\", "/"),
];
private static readonly Regex _Spaces = Spaces();
public static string GetSafeTagName(this string tag)
{
StringBuilder parse = new(tag.ToUpper());
parse = _Replacements.Aggregate(
parse,
(current, replacement) => current.Replace(replacement.Original, replacement.ToReplaceWith));
return _Spaces.Replace(parse.ToString(), " ");
}
private readonly struct Replacement(string original, string toReplaceWith)
{
public string Original { get; } = original;
public string ToReplaceWith { get; } = toReplaceWith;
}
[GeneratedRegex("\\s+", RegexOptions.Compiled)]
private static partial Regex Spaces();
}
StringBuilder. \$\endgroup\$