Replace#
Operations / Transform / Replace
Can Read
Cannot Write
Description#
Replaces every occurrence of a text with another one
Parameters#
| Name | Description |
|---|---|
| Text | The text where the occurrences are searched |
| Find | The text that is searched for |
| Replace | The text that replaces each occurrence found |
| Ignore Case | Whether upper and lower case characters are considered the same |
Code#
using System;
using UnityEngine;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Get]
[Title("Replace")]
[Category("Operations/Transform/Replace")]
[Description("Replaces every occurrence of a text with another one")]
[Image(typeof(IconString), ColorTheme.Type.Yellow, typeof(BadgeSync))]
[Parameter("Text", "The text where the occurrences are searched")]
[Parameter("Find", "The text that is searched for")]
[Parameter("Replace", "The text that replaces each occurrence found")]
[Parameter("Ignore Case", "Whether upper and lower case characters are considered the same")]
[Keywords("Substitute", "Swap", "Change", "Text")]
[Serializable]
public class TypeStringReplace : TypeString
{
[SerializeField] private GetString m_Text = new GetString();
[SerializeField] private GetString m_Find = new GetString();
[SerializeField] private GetString m_Replace = new GetString();
[SerializeField] private GetBool m_IgnoreCase = new GetBool(false);
public override string GetPreview(GameObject source) => Replace(
this.m_Text.GetPreview(source),
this.m_Find.GetPreview(source),
this.m_Replace.GetPreview(source),
this.m_IgnoreCase.GetPreview(source)
);
public override string Get(Args args) => Replace(
this.m_Text.Get(args),
this.m_Find.Get(args),
this.m_Replace.Get(args),
this.m_IgnoreCase.Get(args)
);
private static string Replace(string text, string find, string replace, bool ignoreCase)
{
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(find)) return text ?? string.Empty;
StringComparison comparison = ignoreCase
? StringComparison.OrdinalIgnoreCase
: StringComparison.Ordinal;
return text.Replace(find, replace ?? string.Empty, comparison);
}
public override string ToString()
{
return $"Replace {this.m_Find} with {this.m_Replace}";
}
protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
}
}