javascript - Creating a nested object from parsed bb code -
i trying create object in javascript given string includes bbcode.
var bbstr = 'text [url=http://somelink]links , [i]nested bb code[/i][/url].';
i need recursively iterate through object , transform above string this:
var result = { children : [ { text : 'text ', type : 'text' }, { children: [ { text : 'links , ', type : 'text' }, { text : 'nested bb code', type : 'italic' } ], text : null, type : 'url', url : 'http://somelink' }, { text : '.', type : 'text' } ], type : null, text : null };
then send object rendering function recursively create canvas text it. can't head around, how form object.
try simple stack-based parser:
token = /(?:\[(\w+)(.*?)\])|(?:\[\/(\w+)\])|([^\[\]]+)/g root = {children:[]} stack = [root] bbstr.replace(token, function() { var = arguments; if(a[1]) { var node = {tag: a[1], attr: a[2], children:[]} stack[0].children.push(node); stack.unshift(node); } else if(a[3]) { if(stack[0].tag != a[3]) throw "unmatched tag"; stack.shift(); } else if(a[4]) { stack[0].children.push({tag: "#text", value: a[4]}); } })
the output format differs you've posted, should no problem.
Comments
Post a Comment