Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Markdown in JS without enclosing <p>?

How can I convert a piece of markdown text to HTML using any JS library like markdown-js or marked without enclosing it in paragraph tag?

For example I like to convert this *italic* text to this <i>italic</i> text without enclosing it in <p></p>.

Edit:
- My question is not how to remove p tags from output after conversion, my question is how to ask the library not to enclose output in p tags.
- markdown-js and marked enclose output inside <p></p> by default.

like image 555
Ali Shakiba Avatar asked Dec 27 '14 00:12

Ali Shakiba


2 Answers

The marked library allows you to define your own renderer, which allows you to define the output for paragraphs.

You can pass in your own renderer by using:

marked.setOptions({
  renderer: new MyRenderer(),
});

var output = marked('This **text** will be rendered with MyRenderer');

This will require you to define methods for blockquote, html, paragraph and all the other methods that the default marked.Renderer defines.

Here is an example:

function MyRenderer(options) {
  this.options = options || {};
}

MyRenderer.prototype.paragraph = function(text) {
  return 'This comes from my own renderer: ' + text + '\n';
};

However, this requires some efforts, so the quickest way to get rid of the paragraphs (<p> tags) is to change the code of the existing Renderer in the marked.js file:

Replace:

Renderer.prototype.paragraph = function(text) {
  return '<p>' + text + '</p>\n';
};

With:

Renderer.prototype.paragraph = function(text) {
  return text + '\n';
};
like image 103
Benny Neugebauer Avatar answered Sep 19 '22 12:09

Benny Neugebauer


markdown-it has md.renderInline() method which allows to do that.

like image 45
Roman Pominov Avatar answered Sep 17 '22 12:09

Roman Pominov