For several days I was messing around trying to create a markdown parser. This is the best I could come up without using regex. I was wondering if I'm on the right track.(I only covered the *
,**
case )
var str = "**f*";
function parser() {
var i;
var string = ' ';
for (i = 0; i < str.length; i++) {
if (token(str[i]) !== -1) {
var data = trim(str[i], i);
string += data[0];
if (data[1] === -1) {
string += str[i];
} else {
i = data[1]; //skip if necessary
}
} else {
string += str[i];
}
}
console.log(string);
}
function trim(chr, pos) {
var inner_string = '';
var inner_pos = pos;
if (str[inner_pos] === chr && str[inner_pos + 1] === chr && str[inner_pos + 1] !== undefined) // consecutive tokens
{
var next = pair(chr, pos);
if (next !== -1) {
console.log(next);
inner_string = str.substring(pos + 2, next);
inner_pos = next;
} else {
inner_pos++;
}
} else {
var next = str.indexOf(chr, pos + 1);
if (next > 0) {
console.log(next);
inner_string = str.substring(pos + 1, next);
inner_pos = next;
inner_pos = next;
} else {
inner_pos = next;
}
}
return [inner_string, inner_pos];
}
function pair(char, pos) {
var iter = pos;
while (iter !== str.length - 1) {
iter++;
if (str[iter] === char && str[iter + 1] === char && str[iter + 1] !== undefined) {
return iter;
}
}
return -1;
}
function token(char) {
if (char === '*') {
return 1;
} else return -1;
}
parser();