parseHTML2Vnode

var startReg = new RegExp(/^<[^\/>]+>/);
var selfCloseReg = new RegExp(/^<[^<>\/]+\/>/);
var endReg = new RegExp('^</[^>]+>');
var textNode = new RegExp(/^[^<]+/);

function parse(html) {
    var stack = [];
    var res;
    while (html) {
        var startTag = startReg.exec(html);
        if (startTag) {
            res = startTag[0];
            stack.push(res);
            html = html.slice(res.length);
            continue;
        }
        var textTag = textNode.exec(html);
        if (textTag) {
            res = textTag[0];
            stack.push(res);
            html = html.slice(res.length);
            continue;
        }
        var endTag = endReg.exec(html);
        if (endTag) {
            res = endTag[0];
            stack.push(res);
            html = html.slice(res.length);
            continue;
        }
        var selfCloseTag = selfCloseReg.exec(html);
        if (selfCloseTag) {
            res = selfCloseTag[0];
            stack.push(res);
            html = html.slice(res.length);
            continue;
        }
    }
    return stack;
}

var template = '<div id="main">name</div><span class="loading"><input type="text" />name</span>';

console.log(parse(template));

 

posted @ 2020-09-11 23:10  潴哥  阅读(303)  评论(0编辑  收藏  举报