从HTML中提取文本,同时保留块级元素换行符

 诠释的无耐_999 发布于 2023-02-13 08:09

考虑:

/**
 * Returns the style for a node.
 *
 * @param n The node to check.
 * @param p The property to retrieve (usually 'display').
 * @link http://www.quirksmode.org/dom/getstyles.html
 */
this.getStyle = function( n, p ) {
  return n.currentStyle ?
    n.currentStyle[p] :
    document.defaultView.getComputedStyle(n, null).getPropertyValue(p);
}

/**
 * Converts HTML to text, preserving semantic newlines for block-level
 * elements.
 *
 * @param node - The HTML node to perform text extraction.
 */
this.toText = function( node ) {
  var result = '';

  if( node.nodeType == document.TEXT_NODE ) {
    // Replace repeated spaces, newlines, and tabs with a single space.
    result = node.nodeValue.replace( /\s+/g, ' ' );
  }
  else {
    for( var i = 0, j = node.childNodes.length; i < j; i++ ) {
      result += _this.toText( node.childNodes[i] );
    }

    var d = _this.getStyle( node, 'display' );

    if( d.match( /^block/ ) || d.match( /list/ ) || d.match( /row/ ) ||
        node.tagName == 'BR' || node.tagName == 'HR' ) {
      result += '\n';
    }
  }

  return result;
}

http://jsfiddle.net/3mzrV/2/

也就是说,除了两个例外,迭代每个节点并打印其内容,让浏览器的计算样式告诉您何时插入换行符.

1 个回答
  • 考虑:

    /**
     * Returns the style for a node.
     *
     * @param n The node to check.
     * @param p The property to retrieve (usually 'display').
     * @link http://www.quirksmode.org/dom/getstyles.html
     */
    this.getStyle = function( n, p ) {
      return n.currentStyle ?
        n.currentStyle[p] :
        document.defaultView.getComputedStyle(n, null).getPropertyValue(p);
    }
    
    /**
     * Converts HTML to text, preserving semantic newlines for block-level
     * elements.
     *
     * @param node - The HTML node to perform text extraction.
     */
    this.toText = function( node ) {
      var result = '';
    
      if( node.nodeType == document.TEXT_NODE ) {
        // Replace repeated spaces, newlines, and tabs with a single space.
        result = node.nodeValue.replace( /\s+/g, ' ' );
      }
      else {
        for( var i = 0, j = node.childNodes.length; i < j; i++ ) {
          result += _this.toText( node.childNodes[i] );
        }
    
        var d = _this.getStyle( node, 'display' );
    
        if( d.match( /^block/ ) || d.match( /list/ ) || d.match( /row/ ) ||
            node.tagName == 'BR' || node.tagName == 'HR' ) {
          result += '\n';
        }
      }
    
      return result;
    }
    

    http://jsfiddle.net/3mzrV/2/

    也就是说,除了两个例外,迭代每个节点并打印其内容,让浏览器的计算样式告诉您何时插入换行符.

    2023-02-13 08:20 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有