【问题标题】:Creating a nested object from parsed bb code从解析的 bb 代码创建嵌套对象
【发布时间】:2013-08-24 07:30:49
【问题描述】:

我正在尝试从包含一些 bbcode 的给定字符串在 javascript 中创建一个对象。

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

我需要递归地遍历对象并将上面的字符串转换成这样的:

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
};

然后我会将对象发送到一个渲染函数,该函数将从它递归地创建画布文本。但我就是想不通,如何形成这个对象。

【问题讨论】:

    标签: javascript object bbcode nested


    【解决方案1】:

    试试这个简单的基于堆栈的解析器:

    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]});
        }
    })
    

    输出格式与您发布的不同,但这应该没问题。

    http://jsfiddle.net/L8UZf/

    【讨论】:

    • 这就像一个魅力,看起来非常优雅。我自己的方法真的很臃肿,最后甚至没有奏效。所以,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2021-10-05
    相关资源
    最近更新 更多