Converting a string into a URL-friendly slug
C#, JavaScript and Python examples for turning titles into URL-friendly slugs while handling spaces, punctuation and locale-specific characters.
Turning a title into something usable in a URL (a slug) is fiddlier than it looks: language-specific characters, spaces, punctuation and repeated hyphens all have to be handled. The function below does it in one pass.
Its most critical line is the lowercasing step: if ToLower is called without culture information, the result depends on the server locale. In Turkish the lowercase of capital I is the dotless i, so the same title produces a different slug on a differently configured server. That publishes the same content under two addresses, which search engines treat as a duplicate page.
Things to watch
- Slug generation must live in one place, called both when saving and when building links.
- Uniqueness must be checked separately; append a number when two records share a title.
- If you change a published slug, add a permanent redirect (301) from the old address.
public string urlFormat(string str)
{
if (string.IsNullOrWhiteSpace(str)) { return string.Empty; }
str = str.ToLower(new CultureInfo("tr-TR"));
str = str.Replace("ı", "i")
.Replace("ğ", "g")
.Replace("ü", "u")
.Replace("ş", "s")
.Replace("ö", "o")
.Replace("ç", "c");
str = Regex.Replace(str, @"[^a-z0-9- ]", "");
str = Regex.Replace(str, @"s+", " ");
str = str.Replace(" ", "-");
return str;
}
function urlFormat(str)
{
if (!str || !str.trim()) { return ''; }
str = str.toLowerCase();
str = str.replace(/ı/g, 'i')
.replace(/ğ/g, 'g')
.replace(/ü/g, 'u')
.replace(/ş/g, 's')
.replace(/ö/g, 'o')
.replace(/ç/g, 'c');
str = str.replace(/[^a-z0-9- ]/g, '');
str = str.replace(/\s+/g, ' ');
str = str.replace(/ /g, '-');
return str;
}
import re
def urlFormat(s):
if not s or s.isspace(): return ''
s = s.lower()
s = s.replace('ı', 'i')
.replace('ğ', 'g')
.replace('ü', 'u')
.replace('ş', 's')
.replace('ö', 'o')
.replace('ç', 'c')
s = re.sub(r'[^a-z0-9- ]', '', s)
s = re.sub(r's+', ' ', s)
s = s.replace(' ', '-')
return s
Short guide
When to use it
URL-friendly slug generation is needed for blog posts, product pages, categories and multilingual content. Readable URLs help users understand the page and give search engines cleaner context.
What to watch
- Keep character conversion rules consistent across the project.
- If two records produce the same slug, add a number or short id to prevent collisions.
- When a public URL changes, redirect the old address to the new one.
Common mistake
Changing the URL automatically every time the title changes can break existing links. On published pages, slug changes should be deliberate.
Where this example helps
Small helper snippets like this save time in web applications, mobile app backends, admin panels and API projects. The important part is not copying the example blindly, but adapting it to your data format, security needs and performance expectations.