Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><em><strong>Note:</em></strong> <em>I thought I could come up with a faster solution with a single regex, but I couldn't. Below is my failed method (you can learn from failure), and the results of a performance test, and my conclusion.</em></p> <p>Efficiency can be measured many ways. If you wanted to reduce the number of functions called, then you could use a single regex and a function to handle the replacement.</p> <pre><code>([A-Z])|(\s)|([^a-z\d]) </code></pre> <p><strong><a href="http://rey.gimenez.biz/s/3ifilj" rel="nofollow">REY</a></strong></p> <p>The first group will have <code>toLowerCase()</code> applied, the second will be replaced with a <code>-</code> and the third will return nothing. I originally used <code>+</code> quantifier for groups 1 and 3, but given the expected nature of the text, removing it result in faster execution. <em>(thanks acheong87)</em></p> <pre><code>'Well Done!'.replace(/([A-Z])|(\s)|([^a-z\d])/g, function (match, $0, $1) { if ($0) return String.fromCharCode($0.charCodeAt(0) + 32); else if ($1) return '-'; return ''; }); </code></pre> <p><strong><a href="http://jsfiddle.net/TgFgT/9/" rel="nofollow">jsFiddle</a></strong></p> <p><strong>Performance</strong></p> <p>My method was the worst performing:</p> <pre><code>Acheong87 fastest Original 16% slower Mine 53% slower </code></pre> <p><strong><a href="http://jsperf.com/18335656" rel="nofollow">jsPerf</a></strong></p> <p><strong>Conclusion</strong></p> <p>Your method <em>is the most efficient</em> in terms of code development time, and the performance penalty versus acheong87's method is offset by code maintainability, readability, and complexity reduction. I would use your version unless speed was of the utmost importance.</p> <p>The more optional matches I added to the regular expression, the greater the performance penalty. I can't think of any advantages to my method except for the function reduction, but that is offset by the <code>if</code> statements and increase in complexity.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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