String replace helper for Dust.js

Recently, I’ve been learning about the LinkedIn fork of Dust – a client-side templating solution. Dust allows you to create helpers, which are functions that can be called from within a rendering template. They help separate presentation from logic, which is always a good practice.

Today we created a String Replace helper, which seems like it might be pretty useful for others, so I thought I’d share it.

Following is an example of the helper in use. In this example, the replace helper will replace all instances of a period character with a hyphen in the given message string, and then it will write the trimmed result.

Usage example:

{@replace str="{message}" search="." replace="-" trim="true" /}

Here is the Replace Helper for Dust (also on GitHub Gist)

(function (dust) {
 
    /**
     * Polyfill to create String.trim() if it's not natively available
     */
    if (!String.prototype.trim) {
        (function(){
            // Make sure we trim BOM and NBSP
            var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
            String.prototype.trim = function () {
                return this.replace(rtrim, "");
            }
        })();
    }
 
    /**
     * Processes the given string to escape special meta characters used within
     * Regular Expressions. This is used by the replace helper.
     */
    function escapeRegExp(string) {
        return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
 
    /**
     * Performs a global search and replace within a string.
     * In the following example, we replace all periods in the
     * message string with dashes and we trim the result.
     *
     * {@replace str="{message}" search="." replace="-" trim="true" /}
     *
     * str - the input string within which the search and replace will be performed
     * search - the character or sequence to search
     * replace - the character or sequence used to replace
     * trim - when 'true', will trim the string before returning result.
     *
     */
    dust.helpers.replace = function (chunk, ctx, bodies, params) {
 
        var str = dust.helpers.tap(params.str, chunk, ctx);
        var search = dust.helpers.tap(params.search, chunk, ctx);
        var replace = dust.helpers.tap(params.replace, chunk, ctx);
        var trim = dust.helpers.tap(params.trim, chunk, ctx);
 
        if(trim && trim == 'true') {
            str = str.trim();
        }
 
        var result = str.replace(new RegExp(escapeRegExp(search), 'g'), replace);
 
        return chunk.write( result );
 
    }
 
})(typeof exports !== 'undefined' ? module.exports = require('dustjs-linkedin') : dust);