Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are several things that could be improved in Jeff's solution, though.</p> <pre><code>if (String.IsNullOrEmpty(title)) return ""; </code></pre> <p>IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all.</p> <pre><code>// remove any leading or trailing spaces left over … muuuch later: // remove trailing dash, if there is one </code></pre> <p>Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue.</p> <pre><code>// replace spaces with single dash title = Regex.Replace(title, @"\s+", "-"); // if we end up with multiple dashes, collapse to single dash title = Regex.Replace(title, @"\-{2,}", "-"); </code></pre> <p>Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one.</p> <p>Off the top of my head, without any testing whatsoever, this would be an equivalent solution:</p> <pre><code>// make it all lower case title = title.ToLower(); // remove entities title = Regex.Replace(title, @"&amp;\w+;", ""); // remove anything that is not letters, numbers, dash, or space title = Regex.Replace(title, @"[^a-z0-9\-\s]", ""); // replace spaces title = title.Replace(' ', '-'); // collapse dashes title = Regex.Replace(title, @"-{2,}", "-"); // trim excessive dashes at the beginning title = title.TrimStart(new [] {'-'}); // if it's too long, clip it if (title.Length &gt; 80) title = title.Substring(0, 79); // remove trailing dashes title = title.TrimEnd(new [] {'-'}); return title; </code></pre> <p>Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload