2
\$\begingroup\$

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();
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Why "without using regex"? Just curious \$\endgroup\$
    – Flambino
    Apr 11, 2015 at 19:27
  • \$\begingroup\$ Is all the whitespace intentional or just a bad copy/paste? \$\endgroup\$
    – elclanrs
    Apr 11, 2015 at 21:30
  • \$\begingroup\$ just a bad copy/paste \$\endgroup\$
    – Xtal
    Apr 12, 2015 at 9:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.