From 6a82a743e346fb513ee45c08c4cbd533724620b4 Mon Sep 17 00:00:00 2001 From: Chris Fitzsimons Date: Wed, 20 Nov 2024 23:03:07 +0000 Subject: [PATCH] Not inserting additional newlines when there is leading whitespace fixes #27 --- index.js | 14 +++++++++++--- test.js | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 08f1e41..27a2751 100644 --- a/index.js +++ b/index.js @@ -43,11 +43,19 @@ module.exports = function(str, options) { var re = new RegExp(regexString, 'g'); var lines = str.match(re) || []; + // The regex split will take whitespace from the start of next line, + // and put it on the end of the previous one. Need to move that back. + var extraWhitespace = ''; var result = indent + lines.map(function(line) { - if (line.slice(-1) === '\n') { - line = line.slice(0, line.length - 1); + var fullLine = extraWhitespace + line; + var match = line.match(/^(.+)\n([^\S\n]*)$/s); + if (match) { + fullLine = extraWhitespace + match[1]; + extraWhitespace = match[2]; + } else { + extraWhitespace = ''; } - return escape(line); + return escape(fullLine); }).join(newline); if (options.trim === true) { diff --git a/test.js b/test.js index 42f0a19..0191cd4 100644 --- a/test.js +++ b/test.js @@ -66,4 +66,18 @@ describe('wrap', function () { ' Supercalifragilistic\u200B\n expialidocious' ); }); + + it('should preserve whitespace after a newline', function() { + assert.equal( + wrap('Highlights:\n First\n Second\n Third', { indent: '' }), + 'Highlights:\n First\n Second\n Third' + ); + }); + + it('should preserve whitespace after a newline and handle indents appropriately', function() { + assert.equal( + wrap('Highlights:\n First\n Second\n Third', { indent: '*' }), + '*Highlights:\n* First\n* Second\n* Third' + ); + }); });