Imagine this classic text where you need to replace tokens with some values:
Welcome {{user}}. Click on this link to confirm your subscription: {{url}}.
Tokens encapsulated in double brackets {{token}} are commonly used to mark tokens to be replaced with real values.
It’s simple to make your own token replacer:
using System.Collections.Generic;
namespace MyCode
{
public static class TokenReplacer
{
public static string ReplaceTokens(this string s, Dictionary<string, string> tokens)
{
if (tokens == null)
return s;
foreach (var token in tokens)
s = s.Replace("{{" + token.Key + "}}", token.Value);
return s;
}
}
}
Usage is easy:
var tokenValues = new System.Collections.Generic.Dictionary<string, string>();
tokenValues.Add("user", "briancaos");
tokenValues.Add("url", "https://briancaos.wordpress.com/");
string text = "Welcome {{user}}. Click on this link to confirm your subscription: {{url}}.";
Console.WriteLine(text.ReplaceTokens(tokenValues));
// Output is:
// Welcome briancaos. Click on this link to confirm your subscription: https://briancaos.wordpress.com/.
That’s it. Happy coding.
MORE TO READ:
- Replace {x} tokens in strings from stackoverflow
- C# Remove specific Querystring parameters from URL from briancaos