AS3字符串拆分保持标签

时间:2013-12-20 15:55:20

标签: string actionscript-3 split

我有可以包含标签的变量字符串,例如:

"<b>Water</b>=H<sub>2</sub>O"

我想要的是一个看起来像的数组:

Array[0] <b>Water</b>
Array[1] =H
Array[2] <sub>2</sub>
Array[3] O

我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:0)

给它一个去,它使用一个普通的正则表达式来找到html标签以使它分离,然后使用indexOf和substring将它组合在一起。

function splitWithTags(str:String):Array {

    var tags:Array = str.match(/(<(.|\n)*?>)/g);
    var c:int = tags.length;
    if(c%2 != 0) c--; // if it's odd, decrement to make even so loop works, last tag will be ignored.

    if(c<2) return [str]; // not enough tags so return full string

    var out:Array = [];

    var end:int = 0;
    var pos1:int, pos2:int;

    for(var i:int = 0; i<c; i+=2) {
        // find position of 2 tags.
        pos1 = str.indexOf(tags[i]);
        pos2 = str.indexOf(tags[i+1]);

        if(pos1 >= end+1) { // there's some stuff not between tags to add
            out.push(str.substring(end, pos1));
        }

        end = pos2+tags[i+1].length
        out.push(str.substring(pos1, end));
    }

    if(end < str.length) { // there is substr at end
        out.push(str.substring(end, str.length));
    }

    return out;
}