I'm writing a Markdown parser with ES6:
Input:
# Title
* * *
Paragraph
Another paragraph
Sample code:
// create a find/replace based on a regex and replacement
// to later be used with the conversion functions
function massReplace(text, replacements) {
let result = text
for (let [regex, replacement] of replacements) {
result = result.replace(regex, replacement)
}
return result
}
// match text with # and replace them for html headings
function convertHeadings(text, orig) {
if (orig.match(/^#{1,6}\s/)) {
return massReplace(text,
[/^### (.*)/gm, '<h3>$1</h3>'],
[/^## (.*)/gm, '<h2>$1</h2>'],
[/^# (.*)/gm, '<h1>$1</h1>'] ]
)
}
}
// match text without # and surround them with p tags
function convertParagraphs(text, orig) {
if (!orig.match(/^#{1,6} (.*)/)) {
return `<p>${text}</p>`
}
}
// take the source, split on new lines, make a copy (to
// have a "clean" version to be used in the if statements),
// and finally apply the conversion functions to them with
// the help of a loop and excluding those that output undefined
function convertToHTML(markdownSource) {
let data = markdownSource.split('\n\n')
, orig = data.slice()
, conversions = [ convertHeadings, convertParagraphs]
for (let i = 0, l = orig.length; i < l; ++i) {
for (let conversion of conversions) {
let result = conversion(data[i], orig[i])
if (result !== undefined) {
data[i] = result
}
}
}
return data.join('\n\n')
}
What I want now is to wrap p
tags with the class no-indent
around text that has * * *
preceding it (Paragraph
in the example above). The problem is, I don't know how to get a text based on its preceding one (* * *
in this case).
To give an idea this is the desired output:
<h1>Title</h1>
<p>* * *</p>
<p class="no-indent">Paragraph</p>
<p>Another paragraph</p>