vendredi 20 mars 2015

Why is this else statement being considered first than one of the if values above?

This function loops through an array of strings. If the string doesn't start with an # it's wrapped with a p tag. If the previous string of the string is a # or a * * * it's wrapped with a p tag with the class ni



function replaceParagraphs(data) {
data = data.split('\n\n')
for (var i = 0; i < data.length; ++i) {
if (data[i].match(/^[^#]/g)) {
var content = data[i].replace(/\n(?=\w)/g, ' ').replace(/\n(?=$)/g, '')
if (data[i - 1].match(/^#/g) || data[i - 1] === "* * *") {
data[i] = '<p class="ni">' + content + '</p>'
} else {
data[i] = '<p>' + content + '</p>'
}
}
}
data = data.join('\n\n')

return data
}


But it seems like data[i - 1] === "* * *" is not being considered, since I end up with an output like this:



## Test

<p class="ni">Lorem “ipsum?” dolor ‘sit!’ amet</p>

<p>Consetetur eirmod</p>

<p>* * *</p>

<p>“Ipsum?” “‘dolor’” sit! amet, consetetur eirmod tempor—invidunt ut labore</p>


What could be the problem?


EDIT:


Oh, based on the answers and comments I realized that it's because the code produces <p>* * *</p>


What can I do to prevent this?


Aucun commentaire:

Enregistrer un commentaire