How to use the parse function from marked

Find comprehensive JavaScript marked.parse code examples handpicked from public code repositorys.

marked.parse is a method in the marked.js library that converts markdown text to HTML.

344
345
346
347
348
349
350
351
352
353
354
module.exports = {
	marked : Marked,
	render : (rawBrewText)=>{
		rawBrewText = rawBrewText.replace(/^\\column$/gm, `\n<div class='columnSplit'></div>\n`)
														 .replace(/^(:+)$/gm, (match)=>`${`<div class='blank'></div>`.repeat(match.length)}\n`);
		return Marked.parse(sanatizeScriptTags(rawBrewText));
	},


	validate : (rawBrewText)=>{
		const errors = [];
fork icon294
star icon868
watch icon0

+ 5 other calls in file

130
131
132
133
134
135
136
137
138
139
140
141
             tok.text + '</a>');
    tok.text += '<span><a class="mark" href="#' + id + '" ' +
                'id="' + id + '">#</a></span>';
  });


  toc = marked.parse(toc.join('\n'));
  cb(null, toc);
}


var idCounters = {};
fork icon7
star icon27
watch icon0

How does marked.parse work?

The marked.parse function is a part of the marked library and is used to convert markdown text to HTML, parsing the markdown syntax and converting it to the corresponding HTML. It does this by using a tokenizer to convert the text into tokens and then a renderer to convert the tokens into HTML output. The resulting HTML can then be used to display the formatted text in a web page.

105
106
107
108
109
110
111
112
113
114
  })
);
markdownText = lines.join('\n');

const renderer = new CustomRenderer();
let htmlText = head + marked.parse(markdownText, { renderer }) + tail;
htmlText = htmlText.replace(/^<!-- toc -->$/m, () => renderer.renderTOC());

const htmlFile = path.resolve('../out/docs', markdownFile.replace(/\.md$/, '') + '.html');
console.log(`${markdownFile} => ${htmlFile}`);
fork icon1
star icon16
watch icon0

123
124
125
126
127
128
129
130
131
132
        .replaceAll('%MONOSPACE_FONT%', psname(args['custom-monospace-font']))
        .replaceAll('%DATETIME%', '%DATE% %TIME%')
        .replaceAll('%DATE%', `${d.getFullYear()}-${ps20(d.getMonth() + 1)}-${ps20(d.getDate())}`)
        .replaceAll('%TIME%', `${ps20(d.getHours())}:${ps20(d.getMinutes())}:${ps20(d.getSeconds())}`);
}
const mdParsed = await marked.parse(mdRaw);
const fontToCssSrc = (/** @type {String} */ font) => /\.(tt[fc]|otf|svg|eot|woff2?)$/i.test(font)
    ? `url("file:///${path.resolve(font).replace(/\\/g, '/')}")`
    : `local("${font}")`;

fork icon1
star icon1
watch icon0

+ 2 other calls in file

Ai Example

1
2
3
4
5
const marked = require("marked");
const markdown = "# Hello, world!\n\nThis is **bold** text.";
const html = marked.parse(markdown);
console.log(html);
// Output: Hello, world! \n This is bold text. \n

474
475
476
477
478
479
480
481
482
483
path: '/preview/{fn_key}',
handler: (request, h) => {
	let fn_key = request.params.fn_key;
	let md_cache = string_stores[fn_key];
	if (md_cache) {
		const data = marked.parse(md_cache.string);
		const resp_html =
			'<head>' +
			getStylesheet(fn_key) +
			'</head>' +
fork icon0
star icon3
watch icon1

+ 17 other calls in file

121
122
123
124
125
126
127
128
129
130
131
132


const makePage = function(mdPath, cb) {
    const [startTime, time]  = getTime(mdPath)
    const publishedTime = startTime.toISOString()
    const modifiedTime = time.toISOString()
    const html = marked.parse(readFileSync(mdPath).toString())
    const dir = dirname(mdPath) + '/'
    const url = dir.replace(/\.\/src/, '')


    let title
fork icon0
star icon3
watch icon2

+ 3 other calls in file

34
35
36
37
38
39
40
41
42
43
},
paths: ["./components"],
filters: {
  // {{ "## Parse me" | marked }}
  marked: function(string) {
    return renderMarkdown.parse(string);
  },
  // A filter and non-async version of frctl's context extension from
  // https://github.com/frctl/nunjucks/blob/develop/src/extensions/context.js
  // We mainly use this to make a component's YAML data available to REAMDE.md
fork icon5
star icon2
watch icon5

102
103
104
105
106
107
108
109
110
111

tmp.weekday = group.information.weekday != null ? getWeekdayById(group.information.weekday) : '';

tmp.startTime = group.information.meetingTime != null ? group.information.meetingTime : '';

tmp.note = marked.parse(group.information.note).replace(/"/g,"\"");

tmp.imageUrl = group.information.imageUrl;
tmp.export = getProperty(config.get('export.accessPath.exposureIndicator'), group);
tmp.export = tmp.export === undefined ? false : tmp.export;
fork icon0
star icon0
watch icon0

222
223
224
225
226
227
228
229
230
231
  // like "@static" could have overwritten "ctx.string" again if defined after "@function"
  ctx.isFunction = true;
  break;
case 'return':
  tag.description = tag.description ?
    md.parse(tag.description).replace(/^<p>/, '').replace(/<\/p>\n?$/, '') :
    '';

  // dox does not add "void" / "undefined" to types, so in the documentation it would result in a empty "«»"
  if (tag.string.includes('void') || tag.string.includes('undefined')) {
fork icon0
star icon0
watch icon494

+ 5 other calls in file

217
218
219
220
221
222
223
224
225
226

if (path.extname(fileURL) === '.md') {
    content = marked.parse(fs.readFileSync(fileURL, 'utf8'));
} else {
    const comment = getCommentContent(fileURL);
    content = marked.parse(comment.content);
}

return {
    content: content,
fork icon0
star icon0
watch icon2

+ 3 other calls in file

93
94
95
96
97
98
99
100
101
102
        if (token.type === 'heading' && token.depth === 1) {
            title = token.text;
        }
    }
});
const markdown = marked.parse(fs.readFileSync(filepath, 'utf8'));
const lang = path.extname(path.basename(filename, '.md'))
    .substring(1).toLowerCase();
const html = ejs.render(template, {lang, title, markdown});
fs.writeFileSync(outpath.replace(/\.md$/i, '.html'), html);
fork icon0
star icon0
watch icon0

31
32
33
34
35
36
37
38
39
40

// Interpolate variables within the template body then convert
// to html to be injected into the layout.
let body = templateBody;
body = interpolate(body, vars);
body = marked.parse(body);

const html = interpolate(layoutBody, {
  ...vars,
  content: body,
fork icon0
star icon0
watch icon0

296
297
298
299
300
301
302
303
304
305

var data = {}
var options = {}

if (page_data != '') {
  let processed = marked.parse(page_data.data); // <<-- produces an HTML string

  data.output = DOMPurify.sanitize(processed);
}
else {
fork icon0
star icon0
watch icon0