ASP.NET CoreASP.NET MVCC#

Create SEO friendly URL Slug in C#

class Program
    {
        static void Main(string[] args)
        {
            Urlhelper urlhelper = new Urlhelper();
            var seourl = urlhelper.GenerateSeoFriendlyURL("Create SEO friendly URL in C#");
            Console.WriteLine(seourl);
            Console.Read();
        }
    }
public class Urlhelper
    {
        public string GenerateSeoFriendlyURL(string Title)
        {
            Regex regex = new Regex(@"[^a-zA-Z0-9-\s]", (RegexOptions)0);
            Title = regex.Replace(Title, "");
            Title = Title.ToLower().Replace(" - ", "-");
            Title = Title.ToLower().Replace("- ", "-");
            Title = Title.ToLower().Replace(" -", "-");
            Title = Title.ToLower().Replace("   ", " ");
            Title = Title.ToLower().Replace("  ", " ");
            Title = Title.ToLower().Replace("  ", " ");
            Title = Title.ToLower().Replace(" ", " ");
            Title = Title.ToLower().Replace(" ", "-");
            return Title;
        }
    }

Below points implemented in code

  • Created Urlhelper class
  • Created method GenerateSeoFriendlyURL
  • Pass string to created method
  • Create Regex object with keywords.
  • Add name space usingText.RegularExpressions;
  • Use regex.Replace to string
  • Convert string to lowercase
  • Remove spaces from left and right from string
  • Remove combined hyphen if more than one
Tags
Show More

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Close