diff --git a/index.js b/index.js index 680ec5d..4e4dcaa 100644 --- a/index.js +++ b/index.js @@ -1,10 +1,25 @@ /*! * word-wrap * - * Copyright (c) 2014-2017, Jon Schlinkert. + * Copyright (c) 2014-2023, Jon Schlinkert. * Released under the MIT License. */ +function trimEnd(str) { + let lastCharPos = str.length - 1; + let lastChar = str[lastCharPos]; + while(lastChar === ' ' || lastChar === '\t') { + lastChar = str[--lastCharPos]; + } + return str.substring(0, lastCharPos + 1); +} + +function trimTabAndSpaces(str) { + const lines = str.split('\n'); + const trimmedLines = lines.map((line) => trimEnd(line)); + return trimmedLines.join('\n'); +} + module.exports = function(str, options) { options = options || {}; if (str == null) { @@ -36,7 +51,7 @@ module.exports = function(str, options) { }).join(newline); if (options.trim === true) { - result = result.replace(/[ \t]*$/gm, ''); + result = trimTabAndSpaces(result); } return result; }; diff --git a/package.json b/package.json index 6f8f633..d3e4401 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "word-wrap", "description": "Wrap words to a specified length.", - "version": "1.2.3", + "version": "1.2.4", "homepage": "https://github.com/jonschlinkert/word-wrap", "author": "Jon Schlinkert (https://github.com/jonschlinkert)", "contributors": [ diff --git a/test.js b/test.js index a523bb3..e60fee8 100644 --- a/test.js +++ b/test.js @@ -34,6 +34,10 @@ describe('wrap', function () { assert.equal(wrap(str, {trim: true}), 'A project without documentation is like a project\nthat doesn\'t exist. Verb solves this by making it\ndead simple to generate project documentation,\nusing simple markdown templates, with zero\nconfiguration required.'); }); + it('should trim trailing whitespace (even for empty lines):', function () { + assert.equal(wrap("a \n\nb \n \nc\t", {trim: true}), 'a\n\nb\n\nc'); + }); + it('should handle strings with just newlines', function () { assert.equal(wrap('\r\n', {indent: '\r\n', width: 18}), '\r\n'); });