I have following method(and looks expensive too) for creating permalinks but it’s lacking few stuff that are quite important for nice permalink:
public string createPermalink(string text)
{
text = text.ToLower().TrimStart().TrimEnd();
foreach (char c in text.ToCharArray())
{
if (!char.IsLetterOrDigit(c) && !char.IsWhiteSpace(c))
{
text = text.Replace(c.ToString(), "");
}
if (char.IsWhiteSpace(c))
{
text = text.Replace(c, '-');
}
}
if (text.Length > 200)
{
text = text.Remove(200);
}
return text;
}
Few stuff that it is lacking:
if someone enters text like this:
"My choiches are:foo,bar" would get returned as "my-choices-arefoobar"
and it should be like: "my-choiches-are-foo-bar"
and If someone enters multiple white spaces it would get returned as “—” which is not nice to have in url.
Is there some better way to do this in regex(I really only used it few times)?
UPDATE:
Requirement was:
- Any non digit or letter chars at beginning or end are not allowed
- Any non digit or letter chars should be replaced by “-“
- When replaced with “-” chars should not reapeat like “—“
- And finally stripping string at index 200 to ensure it’s not too long
Change to
If you really want to use regexes, you can do something like this (based on the code of Justin)
The first regex searches for non-word characters (1 or more) at the beginning (
^) or at the end of the string ($) and removes them. The second one replaces one or more non-word characters with-.