Generate Slug - CSharp System

CSharp examples for System:String Algorithm

Description

Generate Slug

Demo Code


using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;//from   w  w  w .  ja v  a2  s .c om

public class Main{
        public static string GenerateSlug(this string phrase)
		{
			string str = phrase.RemoveAccent().ToLower();

			str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // invalid chars           
			str = Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space   
			str = str.Substring(0, str.Length <= 240 ? str.Length : 240).Trim(); // cut and trim it   
			str = Regex.Replace(str, @"\s", "-"); // hyphens   

			return str;
		}
        public static string RemoveAccent(this string txt)
		{
			byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
			return System.Text.Encoding.ASCII.GetString(bytes);
		}
}

Related Tutorials