PROWAREtech

articles » current » dot-net » wordpress-slugs

.NET: How to Create WordPress Slugs

Use C# regular expressions (Regex) to create slugs with only standard characters for use in a URL or other purpose.

Use the regular expression \W+ to replace unwanted URL characters with a dash (-) and prevent multiple dashes running together. In other words, sanitize names and titles.

See also: do this in ASP.NET Core and use JavaScript regular expressions to create WordPress slugs.


namespace ConsoleApp1
{
	class Program
	{
		static void Main(string[] args)
		{
			while (true)
			{
				System.Console.Write("Enter a name to turn into a slug: ");
				var input = System.Console.ReadLine();
				System.Console.WriteLine(System.Text.RegularExpressions.Regex.Replace(input, @"\W+", "-"));
			}
		}
	}
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE