I’m using the Underscore template (which is based on John Resig’s Microtemplate) and whenever I try to replace line breaks inside of it, I get strange behaviors. For example, if I have text like this:
var message = 'Line1\r\n\r\nLine2';
I can properly replace line breaks with br tags if I do this:
$('#example1_no_template').html(message.replace(/\r?\n/g, '<br />'));
However, if I try to replace line breaks inside the Underscore template with the example code below, I don’t get any br tags inserted:
<script id="template1" type="text/html">
<%= message.replace(/\r?\n/g, '<br />') %>
</script>
<script>
var template1 = _.template($('#template1').html());
$('#example1_template').html(template1({ message: message }));
</script>
And strangely, if I change my regular expression inside the template to the following, then I get all kinds of br tags inserted all over the place:
<script id="template3" type="text/html">
<%= message.replace(/[\r\n?]/g, '<br /><br />') %>
</script>
All of these behaviors are shown in this fiddle: http://jsfiddle.net/GHtDY/5/
Any idea what’s going on? Is it possible to replace line breaks inside the template?
I wonder if Underscore’s template parser has a bit of a bug somewhere. If you use the RegExp object syntax instead of the regex literal syntax:
then you start getting the expected results: http://jsfiddle.net/ambiguous/GHtDY/6/
Your “funky output” example:
is coming out funky because Underscore is replacing the n with your
<br>elements. Anyway, that character class is supposed to match any single CR, LF, or question mark and that’s not what you’re trying to do anyway.I suspect that Underscore’s template parser has some problems with some regex literals; you will notice that
/\s/gdoesn’t work as expected either. In particular, it seems to have some trouble parsing escape sequences such as\rand\sinside a regex literal. For example, this:doesn’t work as expected when
messagecontains some digits but usingnew RegExpdoes work as expected.