开发者

How to get a substring from a string variable which is having HTML tags

I have a string variable assigned with some Content in HTML format. Some thing like this var strLabel:String = "This is <b>Test</b>;

But in run time i have get the first 10 characters of the string and display it in another c开发者_运维知识库ontrol. For this, what did was

txtLabelName.Text = String(strLabel).substr(0,10) + ' ...';

But in the output i am getting as This is <b. Basically it considering HTML related tags also as text. But my code has to omit the HTML tags while calculating sub string.

Please anybody help me to do this?


Use this regexp to strip html tags (more or less):

txtLabelName.text = strLabel.replace(/\<.+?\>/g, '').substr(0, 10) + ' ...';

It's a very simple regexp to strip all tags so it won't work on more complex tags (probably).


I got this code from some blog. This is working Perfectly

public static function stripHtmlTags(html:String, tags:String = ""):String
    {
        var tagsToBeKept:Array = new Array();
        if (tags.length > 0)
            tagsToBeKept = tags.split(new RegExp("\\s*,\\s*"));

        var tagsToKeep:Array = new Array();
        for (var i:int = 0; i < tagsToBeKept.length; i++)
        {
            if (tagsToBeKept[i] != null && tagsToBeKept[i] != "")
                tagsToKeep.push(tagsToBeKept[i]);
        }

        var toBeRemoved:Array = new Array();
        var tagRegExp:RegExp = new RegExp("<([^>\\s]+)(\\s[^>]+)*>", "g");

        var foundedStrings:Array = html.match(tagRegExp);
        for (i = 0; i < foundedStrings.length; i++) 
        {
            var tagFlag:Boolean = false;
            if (tagsToKeep != null) 
            {
                for (var j:int = 0; j < tagsToKeep.length; j++)
                {
                    var tmpRegExp:RegExp = new RegExp("<\/?" + tagsToKeep[j] + "( [^<>]*)*>", "i");
                    var tmpStr:String = foundedStrings[i] as String;
                    if (tmpStr.search(tmpRegExp) != -1) 
                        tagFlag = true;
                }
            }
            if (!tagFlag)
                toBeRemoved.push(foundedStrings[i]);
        }
        for (i = 0; i < toBeRemoved.length; i++) 
        {
            var tmpRE:RegExp = new RegExp("([\+\*\$\/])","g");
            var tmpRemRE:RegExp = new RegExp((toBeRemoved[i] as String).replace(tmpRE, "\\$1"),"g");
            html = html.replace(tmpRemRE, "");
        } 
        return html;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜