Skip to content

Instantly share code, notes, and snippets.

@codyburleson
Created October 24, 2014 03:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save codyburleson/eb49a3f69de76e3d752a to your computer and use it in GitHub Desktop.
Save codyburleson/eb49a3f69de76e3d752a to your computer and use it in GitHub Desktop.
String replace helper for Dustjs
(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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment