从 DOM 保留换行符中提取无格式文本的最佳方法
Best way to extract unformatted text from DOM preserving line breaks?
假设我在HTML中TEXT
了以下元素:
<div id="TEXT">
<p>First <strong>Line</strong></p>
<p>Seond <em>Line</em></p>
</div>
应该如何从这个元素中提取原始文本,没有 HTML 标记,但保留换行符?
我知道以下两个选项,但它们似乎都不完美:
-
document.getElementById("TEXT").textContent
- 返回
-
First LineSecond Line
-
- 问题:忽略段落之间应包含的换行符
- 返回
-
document.getElementById("TEXT").innerText
- 返回
-
First Line Second Line
-
- 问题:不是 W3C 标准的一部分,不能保证在所有浏览器中都能正常工作
- 返回
这是一个方便的函数,用于获取任何元素的文本内容,它在所有平台上都运行良好,是的,它保留了换行符。
function text(e){
var t = "";
e = e.childNodes || e;
for(var i = 0;i<e.length;i++){
t+= e[i].nodeType !=1 ? e[i].nodeValue : text(e[i].childNodes);
}
return t;
}
你可以检查jQuery是如何做到的。它使用嘶嘶声js。这是您可以使用的功能。
<div id="TEXT">
<p>First <strong>Line</strong></p>
<p>Seond <em>Line</em></p>
</div>
<script>
var getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
console.log(getText(document.getElementById('TEXT')));
<script>
相关文章:
- Angular指令中的最佳实践是将文本输入设置为英尺和英寸的格式
- HTML + JS:设置文本区域内容样式的最佳方式
- 遍历DOM和替换文本的最佳方法
- 从正则表达式文本中获取正则表达式字符串表示的最佳方式
- 在 html 页面上转换文本的最佳方法
- Javascript从字符串中提取特定文本的最佳方法
- 在 JavaScript 对象文本中组织方法和属性的最佳方式
- 迁移到 Angular 1.3 - 基于模型数据生成视图风格文本 - 最佳方法
- 在不删除内部文本的情况下删除 SPAN 标记的最佳方法
- 在 jsTree 中,使节点文本可单击的最佳方法是什么(用于选中复选框)
- 保存富文本(所见即所得输出)的最佳方法是什么
- 在Javascript中将字符串文本提取为常量是一种最佳实践吗
- 跟踪javascript中文本框控件上触发的退格事件位置的最佳方法
- 屏蔽文本框控件的最佳方式是使用javascript允许字符串值在一对3个字符中
- 用值列表填充文本框的最佳方法是使用java脚本或jquery双击
- 检查3个文本框是否为空的最佳方法
- 创建简单的富文本所见即所得编辑器的最佳方法是什么?
- 在body html中搜索某些文本的最佳方法是什么?
- 实现文本大小可访问性特性的最佳方法是什么?
- 这是在文本框中输入数字的最佳方法