A URL-friendly string is a URL-encoded version of a string that is easy for both users and search engines to read. This generally means transforming a string (like a title or a name) into a lowercase, hyphen-separated format, free of special characters or spaces. Let's look at some examples and best practices in detail.
Lowercase Letters: URLs are case-sensitive, so using lowercase letters ensures uniformity.
Spaces Converted to Hyphens: Spaces in URLs should be replaced by hyphens (-), as underscores (_) are often not SEO-friendly and can be misinterpreted by search engines.
No Special Characters: Remove or replace characters like !, @, #, $, etc., because they might not be URL-safe or might cause issues in browsers.
Diacritical Marks Normalized: Accented characters (e.g., é, ç, ü) should be replaced by their non-accented equivalents (e.g., e, c, u).
Trim Leading/Trailing Hyphens: It's important to ensure the final string doesn't start or end with a hyphen.
1. Simple Titles
Original Title ==> URL-Friendly Slug
My First Blog Post ==> my-first-blog-post
A Quick Guide to SEO ==> a-quick-guide-to-seo
ASP.NET Core: The Complete Guide ==> aspnet-core-the-complete-guide
2. Titles with Special Characters
Original Title ==> URL-Friendly Slug
Hello, World! ==> hello-world
Learn @ ASP.NET Core ==> learn-aspnet-core
C# & ASP.NET Core ==> csharp-aspnet-core
3. Titles with Accents or Non-English Characters
Original Title ==> URL-Friendly Slug
Café au Lait ==> cafe-au-lait
Naïve Bayes Classifier ==> naive-bayes-classifier
José's Java ==> joses-java
Crème brûlée ==> creme-brulee
4. Titles with Numbers
Original Title ==> URL-Friendly Slug
Top 10 Tips for Coding ==> top-10-tips-for-coding
Version 2.0 Release Notes ==> version-20-release-notes
2018 Annual Report ==> 2018-annual-report
5. Titles with Multiple Spaces, Dashes, or Punctuation
Original Title ==> URL-Friendly Slug
Hello World ==> hello-world
This---is a test! ==> this-is-a-test
Version 2.0_ Update! ==> version-20-update
Post...About...ASP.NET! ==> post-about-aspnet
6. Long Titles or Descriptions
Original Title ==> URL-Friendly Slug
How to Build a Scalable and Reliable Application with ASP.NET Core
how-to-build-a-scalable-and-reliable-application-with-aspnet-core
Introduction to Machine Learning with Python: A Comprehensive Guide
introduction-to-machine-learning-with-python-a-comprehensive-guide
Spaces → Hyphens
Always replace spaces with hyphens (-). Spaces can break URLs, and hyphens improve readability.
Remove Special Characters
Characters like !, @, #, and % are not URL-safe. These should be removed or replaced with acceptable characters (e.g., & can become and, % can be removed).
Lowercase
Always convert to lowercase to avoid case sensitivity issues in URLs and ensure consistency. For example, "My Great Post" should be "my-great-post", not "My-Great-Post".
Normalize Accented Characters
Accented characters like é, ç, ü, etc., should be replaced with their basic equivalents (e.g., é → e, ç → c, ü → u).
Avoid Consecutive Hyphens
If the original string has multiple consecutive spaces or special characters, remove or replace them with a single hyphen (-).
Trim Leading/Trailing Hyphens
Ensure that your URL doesn’t begin or end with a hyphen. For instance, " Hello, World! " should become "hello-world", not "-hello-world-".
SEO (Search Engine Optimization):
Search engines prefer clean, readable, and descriptive URLs. Slugs that accurately reflect the content of the page improve the chances of the page being indexed properly.
User Experience:
URL-friendly slugs are easier to remember, share, and type. For example, www.example.com/blog/my-first-post is far more user-friendly than www.example.com/blog/post?id=123.
Compatibility:
Some characters may not be properly encoded by browsers or web servers. Removing or replacing special characters ensures maximum compatibility across different environments.
If you're building an ASP.NET Core MVC application, you would typically use these URL-friendly slugs as part of your routing.
You can create a utility method to convert strings into slugs (URL-friendly format). Here's an example:
public static class SlugHelper
{
public static string ToSlug(this string title)
{
if (string.IsNullOrWhiteSpace(title))
{
return string.Empty;
}
// Remove any unwanted characters and normalize the string
title = title.ToLowerInvariant();
// the same for other vietnamese characters
title = title.Replace("đ", "d");
title = Regex.Replace(title, @"[ôốồổỗộơớởờỡợ]", "o");
title = title.Normalize(NormalizationForm.FormD) // Decompose characters (like é -> e)
.Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark) // Remove diacritic marks
.Aggregate(string.Empty, (current, c) => current + c);
// Replace spaces with hyphens and remove non-alphanumeric characters
title = Regex.Replace(title, @"[^a-z0-9\s-]", "")
.Trim()
.Replace(' ', '-');
// Remove duplicate hyphens
title = Regex.Replace(title, @"-+", "-");
return title;
}
}
You can use this method in your controller to generate a URL-friendly slug from a title.
public class PostsController : Controller
{
public IActionResult Create()
{
var postTitle = "My First Blog Post!";
var slug = postTitle.ToSlug();
// Now you can use the slug in your URLs
return Content($"Generated Slug: {slug}");
}
}
If you were to pass a title like "My First Blog Post!" through the ToSlug method, it would return "my-first-blog-post", which can then be used in a URL like:
https://yourdomain.com/posts/my-first-blog-post
To use slugs in your routing, you would configure your route to accept the slug as a parameter. For example, you can create a route for viewing a specific post:
[HttpGet("posts/{slug}")]
public class PostsController : Controller
{
public IActionResult Details(string slug)
{
// Use the slug to find the post in the database
var post = _postRepository.GetPostBySlug(slug);
// Or user can filter product by slug
var post = _context.Posts.SingleOrDefault(p => p.Title.ToSlug() == slug);
if (post == null)
{
return NotFound();
}
return View(post);
}
}
Usage in Views:
If you want to create a URL for a blog post using its slug in a view (e.g., in a Razor view), you can use the Url.Action method to generate the URL dynamically:
csharp
Copy code
<a href="~/posts/@post.ToSlug()">Read more</a>
URL-friendly slugs should be lowercase, hyphen-separated, and free of special characters or spaces.
Use slug generation functions to ensure consistent formatting for URLs.
Search engines and users prefer simple, readable URLs.
Always consider normalizing special characters, and removing redundant punctuation to maintain clean and effective slugs.