Skip to content

Instantly share code, notes, and snippets.

@sylvaindethier
Created May 6, 2014 18:26
Show Gist options
  • Save sylvaindethier/a5f7435af4eda9e9b474 to your computer and use it in GitHub Desktop.
Save sylvaindethier/a5f7435af4eda9e9b474 to your computer and use it in GitHub Desktop.
Handlebars helper new line to br
/**
* Replace \n by <br />, such as the `nl2br` in PHP
* @see http://stackoverflow.com/questions/2919337/jquery-convert-line-breaks-to-br-nl2br-equivalent
*/
Handlebars.registerHelper('nl2br', function (text, isXhtml) {
var breakTag = (isXhtml || typeof isXhtml === 'undefined') ? '<br />' : '<br>';
return (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
});
@jitendra-1217
Copy link

👍

@dhollenbeck
Copy link

dhollenbeck commented Nov 5, 2016

@EyMaddis
Copy link

EyMaddis commented Mar 8, 2021

this version reuses the internals from Handlebars in accordance with the docs:

Handlebars.registerHelper('nl2br', function(text, isXhtml) {
  const breakTag = isXhtml ? '<br />' : '<br>'
  const withBr = Handlebars.escapeExpression(text).replace(
    /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,
    '$1' + breakTag + '$2'
  )
  return new Handlebars.SafeString(withBr)
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment