The following code reads a file, splits its data, replaces some characters in the data, and then joins the data again:
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err
data = data.split('\n\n')
var tree = data.slice()
for (var i = 0; i < tree.length; ++i) {
if (tree[i].match(/^#/g)) {
data[i] = data[i]
.replace(/^#### (.*)/gm, '<h4>$1</h4>')
.replace(/^### (.*)/gm, '<h3>$1</h3>')
.replace(/^## (.*)/gm, '<h2>$1</h2>')
.replace(/^# (.*)/gm, '<h1>$1</h1>')
}
if (tree[i].match(/"|'/g)) {
data[i] = data[i]
.replace(/"(?=\b|\*|')/g, '“')
.replace(/"(?!\b|\*|')/g, '”')
.replace(/'(?!\b|\*)|(?=\b)'(?=\b)/g, '’')
.replace(/'(?=\b|\*)/g, '‘')
}
if (tree[i].match(/--/g)) {
data[i] = data[i]
.replace(/\b--(\b)*/g, '—')
}
if (tree[i].match(/\*\*|\*/g)) {
data[i] = data[i]
.replace(/\*\*([^\*|\s]+)\*\*/g, '<strong>$1</strong>')
.replace(/\*([^\*|\s]+)\*/g, '<em>$1</em>')
}
if (tree[i].match(/^[^#]/g)) {
if (tree[i - 1] && (tree[i - 1].match(/^#/g) || tree[i - 1] === "* * *")) {
data[i] = '<p class="ni">' + data[i] + '</p>'
} else {
data[i] = '<p>' + data[i] + '</p>'
}
}
}
data = data.join('\n\n')
saveHtml(data)
})
Example input:
# Title
'Single quotes'
"Double Quotes"
* * *
Paragraphs
Output:
<h1>Title</h1>
<p class="ni">‘Single quotes’</p>
<p>“Double Quotes”</p>
<p>* * *</p>
<p class="ni">Paragraphs
</p>
Is there a cleaner way to write those if statements? Or at least create a function so that there is less code in that fs.readFile
block?
Aucun commentaire:
Enregistrer un commentaire