Slugify - CSharp System

CSharp examples for System:String Algorithm

Description

Slugify

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from w ww  . j a va  2s  .co m

public class Main{
        public static string Slugify(this string stringObj)
		{
			if (!string.IsNullOrWhiteSpace(stringObj))
			{
				string validCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXWZ1234567890 -";

				string slugified = stringObj.ToLower().Trim().Replace("  ", " ").Replace("/", "-").Replace(" - ", "-").Replace(' ', '-').Replace("--", "-").Replace("&", "and").Replace("%", "percent");

				foreach (var character in slugified)
				{
					if (!validCharacters.Contains(character))
					{
						slugified = slugified.Replace(character + "", "");
					}
				}

				return slugified;
			}
			return stringObj;
		}
}

Related Tutorials