Markdown in JS without the <p> application?

How to convert a part of the text of labels to HTML using any JS library, such as markdown-js or marked without inclusion in the paragraph tag?

For example, I like to convert this *italic* text to this <i>italic</i> text without wrapping 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 by default marked output inside <p></p> .

+6
source share
4 answers

markdown-it has an md.renderInline () method that allows this.

+6
source

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

You can transfer your own render with:

 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 other methods that are defined by marked.Renderer by default.

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 effort, so a quick way to get rid of paragraphs ( <p> tags) is to change the code of an existing Renderer in marked.js file:

Replace:

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

WITH

 Renderer.prototype.paragraph = function(text) { return text + '\n'; }; 
+10
source

I got around this using a regex for the result:

 rawMarkup.replace(/^(?:<p>)?(.*?)(?:<\/p>)?$/, "$1") 

However, it only works in simple cases , and will fail in cases where there are two adjacent paragraphs and possibly others.

After some testing, I realized that there is a good reason why there are paragraph tags around the text and that my implementation will have to adapt.

+1
source

I was a bit late for the game on this issue, but yesterday I had the same problem, and I opened the marked one to create a solution to this problem.

I need (for my i18n translation CMS) to insert tags inside any type of tags, for example headers, and render them from Markdown without the attached <p> . Therefore, this fix makes it so that if there is only one line of text in my source (for me it is JSON), it will not be inserted into the <p> tags. But if there are more, they will wrap them all in tags as usual.

Here is my change request for change https://github.com/chjj/marked/pull/841

I very much doubt that it will be included, but I use it in my project and it works great.

+1
source

Source: https://habr.com/ru/post/980189/


All Articles