解析数组中的内容

时间:2010-11-10 13:39:06

标签: javascript html parsing

我只需要从某个数组中获取文本。所以我需要解析它。我有以下代码:

for(var x=0;x<contentArray.length;x++){
markup += '<td>'+contentArray[x+1] +'</td>'; 
x++;
}

其中给出了以下输出:

<td><c>&lt;ul&gt;&lt;li&gt;The content text&lt;/li&gt;&lt;/ul&gt;</c></td>

它就像这样浏览浏览器:

<ul><li>The content text</li></ul>

现在我想只得到文本(内容文本&amp;在这种情况下)。我怎么能做针锋相对?

1 个答案:

答案 0 :(得分:2)

您可以使用此功能来取消HTML(从Prototype源代码中窃取):

function unescapeHTML(html) {
    return html
               .replace(/&lt;/g,'<')
               .replace(/&gt;/g,'>')
               .replace(/&amp;/g,'&');
}

然后,您可以使用jQuery的解析功能从标记中获取文本:

for(var x=0;x<contentArray.length;x++){
    var $el = $(unescapeHTML(contentArray[x+1])).find('li'); //use the unescaped HTML to construct a jQuery object and find the li tag within it

    markup += '<td>' + $el.text() + '</td>'; // get the text from the jQuery object and insert it into the fragment
    x++;
}