Sanitize#
Operations / Transform / Sanitize
Can Read
Cannot Write
Description#
Keeps letters and digits only, turns every whitespace run into a separator and drops the rest
Parameters#
| Name | Description |
|---|---|
| Text | The text that is sanitized |
| Separator | The character that replaces each run of whitespaces |
| Lower Case | Whether the result is also converted to lower case |
Code#
using System;
using System.Text;
using UnityEngine;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Get]
[Title("Sanitize")]
[Category("Operations/Transform/Sanitize")]
[Description("Keeps letters and digits only, turns every whitespace run into a separator and drops the rest")]
[Image(typeof(IconFilter), ColorTheme.Type.Yellow)]
[Parameter("Text", "The text that is sanitized")]
[Parameter("Separator", "The character that replaces each run of whitespaces")]
[Parameter("Lower Case", "Whether the result is also converted to lower case")]
[Keywords("Slug", "Url", "Clean", "Escape", "Safe", "Identifier", "Text")]
[Serializable]
public class TypeStringSanitize : TypeString
{
[SerializeField] private GetString m_Text = new GetString();
[SerializeField] private GetString m_Separator = new GetString("-");
[SerializeField] private GetBool m_LowerCase = new GetBool(true);
[NonSerialized] private readonly StringBuilder m_Builder = new StringBuilder();
public override string Get(Args args)
{
string text = this.m_Text.Get(args);
if (string.IsNullOrEmpty(text)) return string.Empty;
string separator = this.m_Separator.Get(args) ?? string.Empty;
bool lowerCase = this.m_LowerCase.Get(args);
this.m_Builder.Clear();
bool pendingSeparator = false;
foreach (char character in text)
{
if (char.IsLetterOrDigit(character))
{
if (pendingSeparator && this.m_Builder.Length > 0) this.m_Builder.Append(separator);
this.m_Builder.Append(lowerCase ? char.ToLowerInvariant(character) : character);
pendingSeparator = false;
continue;
}
if (char.IsWhiteSpace(character)) pendingSeparator = true;
}
return this.m_Builder.ToString();
}
public override string ToString()
{
return $"Sanitize {this.m_Text}";
}
protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
}
}