如何从HTML标记中提取文本

4

我正在尝试获取用户输入的html数据中的每个文本

我有以下这样的html

  <em>first part</em> of texts here

    <table>
    ......
    ......
    </table>

<em>second part</em> of texts

我使用jQuery。
project =[];

$(htmlData).contents().each(function(){
     if($(this).is('table')){
        //do something with table
     }else{
        if(this.nodeType === 3) { // Will only select element nodes
                  project.push($(this).text());
            }else if(this.nodeType === 1){
                  project.push(this.outerHTML);
            }
         }
     }

数组最终形成如下所示。
array(0=>'<em>first part</em>', 2=>'of texts here',3=>'<em>second part</em>',4=>'of texts')

我希望能够获得以下形式的数组:

array(0=>'<em>first part</em>of texts here',1=>'<em>second part</em>of texts');

如何实现这个?感谢您的帮助!

数组元素应该如何分隔。示例中说数组应该只有一个元素。那么不使用数组,而是使用字符串作为累加器,是不是更好呢? - Lee Avital
2个回答

1

演示: http://jsfiddle.net/Cbey9/2/

var project =[];

$('#htmlData').contents().each(function(){
    if($(this).is('table')){
        //do something with table
    }else{
        var txt = (
                this.nodeType === 3  ?  $(this).text()  :
                (this.nodeType === 1  ?  this.outerHTML  :  '')
            ).replace(/\s+/g,' ') // Collapse whitespaces
            .replace(/^\s/,'') // Remove whitespace at the beginning
            .replace(/\s$/,''); // Remove whitespace at the end
        if(txt !== ''){ // Ignore empty
            project.push(txt);
        }
    }
});

我理解您的问题有些困难。如果您想在表格中进行拆分,那么可以使用:
var project =[''];

$('#htmlData').contents().each(function(){
    if($(this).is('table')){
        project.push('');
        //do something with table
    }else{
        project[project.length-1] += (
            this.nodeType === 3  ?  $(this).text()  :
            (this.nodeType === 1  ?  this.outerHTML  :  '')
        );
    }
});
for(var i=0; i<project.length; ++i){
    project[i] = project[i].replace(/\s+/g,' ') // Collapse whitespaces
    .replace(/^\s/,'') // Remove whitespace at the beginning
    .replace(/\s$/,''); // Remove whitespace at the end
}

演示: http://jsfiddle.net/Cbey9/3/


谢谢,但它没有返回我需要的内容。你的fiddle有<em>第一部分</em>,这里是一些文本,<em>第二部分</em>,这里也是一些文本,但我需要<em>第一部分</em>这里的文本,<em>第二部分</em>这里的文本,总共只有2个元素,而不是4 + 1。 - FlyingCat
@FlyingCat 啊,抱歉,我以为我理解了你的问题,但实际上没有。那么,我不明白为什么“<em>这里是文本的第一部分</em>”应该在一起。你到底想在哪里分割? - Oriol
我想从<table>元素中分离出基于HTML的内容。因此,如果我们有texts1...<table><em>texts</em>2...<table>texts3.... 我想要"<texts...,<em>texts</em>2...,texts3..."。抱歉,我应该更具体些。 - FlyingCat

1
将要放置的文本放入具有特定类的span中(不会改变布局):
<span class="phrase"><em>first part</em> of texts here</span>

    <table>
    ......
    ......
    </table>

<span class="phrase"><em>second part</em> of texts</span>

然后你可以得到它们:

$('span.phrase').each(function() {
    project.push($(this).html());
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接