1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| var templateStr = '<div><p id="div" class="box p">aaa</p><ul><li>a</li><li>b</li><li>c</li></ul></div>'; parseHtml(templateStr)
function parseHtml(templateStr) { var index = 0; var stackTag = []; var stackContent = [{'children': []}]; var rest = templateStr; var startRegExp = /^\<([a-z]+[1-6]?)(\s[^\<]+)?\>/; var endRegExp = /^\<\/([a-z]+[1-6]?)\>/; var wordRegExp = /^([^\<]+)\<\/[a-z]+[1-6]?\>/; while (index < templateStr.length - 1) { rest = templateStr.substring(index) if (startRegExp.test(rest)) { let tag = rest.match(startRegExp)[1]; let attrString = rest.match(startRegExp)[2]; stackTag.push(tag); stackContent.push({'tag': tag, 'children': [],'attrs':parseAttrString(attrString)}); index += tag.length + 2 + (attrString != null?attrString.length:0); } else if (endRegExp.test(rest)) { let tag = rest.match(endRegExp)[1]; let pop_tag = stackTag.pop(); if (tag == pop_tag) { let pop_arr = stackContent.pop(); if (stackContent.length > 0) { stackContent[stackContent.length - 1].children.push(pop_arr); } } else { throw new Error(stackTag[stackTag.length - 1] + "没有闭合") } index += tag.length + 3; } else if (wordRegExp.test(rest)) { let word = rest.match(wordRegExp)[1]; if (!/^\s+$/.test(word)) { stackContent[stackContent.length - 1].children.push({'text': word, 'type': 3}) } index += word.length; } else { index++; } } console.log(stackContent[0].children[0]) }
function parseAttrString(attrString) { if(attrString == undefined)return []; var isYinhao = false; var point = 0; var result = []; for (var i = 0;i<attrString.length;i++){ let char = attrString[i]; if(char == '"'){ isYinhao = !isYinhao; }else if (char == ' ' && !isYinhao){ if(!/^\s*$/.test(attrString.substring(point,i))) { result.push(attrString.substring(point,i).trim()); point = i; } } } result.push(attrString.substring(point).trim())
result = result.map(item => { let o = item.match(/^(.+)="(.+)"$/); return { name: o[1], value: o[2] } }) return result }
|