diff --git a/cli.js b/cli.js index 87dd4c0..2ef6063 100755 --- a/cli.js +++ b/cli.js @@ -37,7 +37,7 @@ if (args._.length !== 1) { '', ' --no-stripHeadingTags: Do not strip extraneous HTML tags from heading', ' text before slugifying', - '', + '', ' --indent: Provide the indentation to use - defaults to \' \'', ' (to specify a tab, use the bash-escaped $\'\\t\')' ].join('\n')); @@ -74,5 +74,5 @@ input.on('error', function onErr(err) { function output(parsed) { if (args.json) return console.log(JSON.stringify(parsed.json, null, ' ')); - process.stdout.write(parsed.content); + process.stdout.write(parsed.content+'\n'); } diff --git a/index.js b/index.js index 90cb8be..fecb946 100644 --- a/index.js +++ b/index.js @@ -187,6 +187,9 @@ function linkify(tok, options) { opts.num = tok.seen; var text = titleize(tok.content, opts); var slug = utils.slugify(tok.content, opts); + + var slug = clearToken(slug, '#'); + var text = stripMarkdownLink(text); slug = querystring.escape(slug); if (opts && typeof opts.linkify === 'function') { return opts.linkify(tok, text, slug, opts); @@ -196,6 +199,42 @@ function linkify(tok, options) { return tok; } +/** + * Removes a given token from the string returning the new value. + * + * @param {String} token + * @param {String} delimiter + * @return {String} cleaned token + */ + +function clearToken(token, delimiter) { + var new_token + if(token.indexOf(delimiter) != -1) { + new_token = token.substring(0, token.lastIndexOf(delimiter)).trim(); + } + else { + new_token = token + } + // console.log('Before: ' + token) + // console.log('After : ' + new_token) + return new_token +} + +/** + * Regex match markdown link + * https://stackoverflow.com/questions/37462126/regex-match-markdown-link + * + * @param {String} text + * @return {String} stripped text + */ +function stripMarkdownLink(text) { + // var str = String(text).replace(/__|\*|\#|(?:\[([^\]]*)\]\([^)]*\))/gm, '$1').trim(); + var str = String(text).replace(/__|\*|\#|(?:\[([^\]]*)\]\([^)]*\))/gm, '').trim(); + // console.log('Before: ' + text) + // console.log('After : ' + str) + return str; +} + /** * Titleize the title part of a markdown link. * diff --git a/test/test.js b/test/test.js index e93e41b..034d628 100644 --- a/test/test.js +++ b/test/test.js @@ -128,6 +128,7 @@ describe('options: custom functions:', function() { return str.indexOf('...') === -1; } }); + // console.log('actual.content: \n' + actual.content) assert.equal(actual.content, [ '- [AAA](#aaa)', ' * [a.1](#a1)', @@ -343,6 +344,11 @@ describe('toc', function() { '- [ddd](#fez-ddd)' ].join('\n')); }); + + it('should strip out links and html on headings', function() { + assert.equal(toc('## Title [Go](#ite)').content, '- [Title](#title-go)'); + assert.equal(toc('## Title [Go]').content, '- [Title [Go]](#title-go)'); + }); }); describe('toc tokens', function() {