I am trying to create an object in javascript from a given string which includes some bbcode.

var bbStr = 'Text with [url=http://somelink]links and [i]nested bb code[/i][/url].';

I need to recursively iterate through the object and transform the above string into something like this:

var result = {
  children : [
    {
      text : 'Text with ',
      type : 'text'
    },
    {
      children: [
        {
          text : 'links and ',
          type : 'text'
        },
        {
          text : 'nested bb code',
          type : 'italic'
        }
      ],
      text : null,
      type : 'url',
      url  : 'http://somelink'
    },
    {
      text : '.',
      type : 'text'
    }
  ],
  type : null,
  text : null
};

Then I would send the object to a rendering function which would recursively create canvas text from it. But I just can't get my head around, how to form this object.

有帮助吗?

解决方案

Try this simple stack-based parser:

token = /(?:\[(\w+)(.*?)\])|(?:\[\/(\w+)\])|([^\[\]]+)/g
root = {children:[]}
stack = [root]

bbStr.replace(token, function() {
    var a = 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 from what you've posted, but that should be no problem.

http://jsfiddle.net/L8UZf/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top