× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

JavaScripts Best Practices, there is always a shorter way vol.3

Emre Sakarya
Jan 14, 2017
<p> </p> <p>There are always many ways that take you to your target. But some of them shorter than others. Short ways are also preferable not only because it's short but also it's easy to catch and debug errors.</p> <p> </p> <p><strong>Sample issue:</strong></p> <p>You have a string that you need to replace all "-" with ",":</p> <p><span style="background-color:rgb(255, 255, 255); color:rgb(95, 99, 102)">A solution :</span></p> <pre><code class="language-javascript"> function replaceAll(str){ while(str.indexOf('-')&gt;0){ str=str.replace('-',','); } return str; } replaceAll('foo-bar-baz'); // outputs foo,bar,baz</code></pre> <p> </p> <p>This is actually ok, but how about this:</p> <pre><code class="language-javascript">'foo-bar-baz'.split('-').join(','); // outputs foo,bar,baz</code></pre> <p>And now bring it one step further and make it available to everywhere. Make it a Polyfill like this :</p> <pre><code class="language-javascript">String.prototype.replaceAll=function(find,replace){ return this.split('-').join(','); } 'foo-bar-baz'.replaceAll('-',','); // returns "foo,bar,baz"</code></pre> <p> </p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus