使用间距检索内部文本

时间:2014-02-26 01:14:41

标签: javascript jquery

我想从任意HTML块中提取文本。天真的尝试:

$('<div><p>Some</p>Inner<div>Text</div></div>').text()

这会SomeInnerText,但我想要Some Inner Text

什么是从HTML中提取文本的更好方法,同时保留用于呈现HTML的可视化结构的一些概念?

在上面的示例中,块元素之间的新行很棒&amp;空格可能是一种“扁平”的输出。

4 个答案:

答案 0 :(得分:1)

您可以在脚本中插入“&amp; nbsp”:

$('<div><p>Some&nbsp;</p>Inner&nbsp;<div>Text</div></div>').text();

答案 1 :(得分:1)

好吧,你可以扩展jQuery来做到这一点:

$.fn.textRespectingBlocks = function() {
    return this.map(function() {
        var $this = $(this);
        var display = $this.css('display');
        var isBlock = display !== 'none' && display !== 'inline' && display !== 'inline-block' && display !== 'inline-flex' && display !== 'inline-table';
        var childText = Array.prototype.map.call(this.childNodes, function(node) {
            if (node.nodeType === 1) {
                return $(node).textRespectingBlocks();
            }

            if (node.nodeType === 3) {
                return node.nodeValue;
            }

            return '';
        }).join('');

        return isBlock ? ' ' + childText + ' ' : childText;
    }).get().join('');
};

如果您愿意,请对结果进行.replace(/^\s+|\s+$|\s(?=\s)/g, '')

答案 2 :(得分:1)

在关闭标记之前使用正则表达式注入空格:

$('<div><p>Some</p>Inner<div>Text</div></div>'.replace(/</g, ' <')).text();

小提琴:http://jsfiddle.net/mattdlockyer/uau6S/

答案 3 :(得分:0)

只需自己添加空间即可。但是,由于不同浏览器解析html的方式不同,这可能会导致浏览器中的空白区域发生变化。

$('<div> <p>Some</p> Inner <div>Text</div></div>').text()
相关问题