diff --git a/README.md b/README.md index 00573e9..24074cc 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,8 @@ You can configure the behaviour of html-to-text with the following options: By using the `format` option, you can specify formatting for these elements: `text`, `image`, `lineBreak`, `paragraph`, `anchor`, `heading`, `table`, `orderedList`, `unorderedList`, `listItem`, `horizontalLine`. +A catch-all key `otherTag` may be used to specify a formatter for tags that aren't covered by one of the other keys. + Each key must be a function which eventually receive `elem` (the current elem), `fn` (the next formatting function) and `options` (the options passed to html-to-text). ```js diff --git a/lib/formatter.js b/lib/formatter.js index ef2e82d..e2e7cde 100644 --- a/lib/formatter.js +++ b/lib/formatter.js @@ -254,6 +254,10 @@ function formatBlockquote(elem, fn, options) { return '> ' + fn(elem.children, options) + '\n'; } +function formatOtherTag(elem, fn, options) { + return fn(elem.children, options); +} + exports.text = formatText; exports.image = formatImage; exports.lineBreak = formatLineBreak; @@ -266,3 +270,4 @@ exports.unorderedList = formatUnorderedList; exports.listItem = formatListItem; exports.horizontalLine = formatHorizontalLine; exports.blockquote = formatBlockquote; +exports.otherTag = formatOtherTag; diff --git a/lib/html-to-text.js b/lib/html-to-text.js index 6a77039..55a8f18 100644 --- a/lib/html-to-text.js +++ b/lib/html-to-text.js @@ -164,7 +164,7 @@ function walk(dom, options, result) { result += format.blockquote(elem, walk, options); break; default: - result = walk(elem.children || [], options, result); + result += format.otherTag(elem, walk, options); } break; case 'text': diff --git a/test/html-to-text.js b/test/html-to-text.js index af7f7aa..841c01b 100644 --- a/test/html-to-text.js +++ b/test/html-to-text.js @@ -367,15 +367,20 @@ describe('html-to-text', function() { describe('custom formatting', function () { it('should allow to pass custom formatting functions', function () { - var result = htmlToText.fromString('

TeSt

', { + var result = htmlToText.fromString('

TeSt

tag
', { format: { heading: function (elem, fn, options) { var h = fn(elem.children, options); - return '====\n' + h.toLowerCase() + '\n===='; + return '====\n' + h.toLowerCase() + '\n====\n'; + }, + + otherTag: function (elem, fn, options) { + var div = fn(elem.children, options); + return '----\n' + div.toUpperCase() + '\n----'; } } }); - expect(result).to.equal('====\ntest\n===='); + expect(result).to.equal('====\ntest\n====\n----\nTAG\n----'); }); });