将HTML转换为纯文本同时保留换行符(使用JavaScript)最方便的方法是什么? [英] What is the most convenient way to convert HTML to plain text while preserving line breaks (with JavaScript)?

查看:164
本文介绍了将HTML转换为纯文本同时保留换行符(使用JavaScript)最方便的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我只需要从浏览器窗口中复制该HTML并将其粘贴到textarea元素中的效果。



例如,我想要这个:

 < p>一些< / p> 
< div>文字< br />一些< / div>
< div>文字< / div>

变成这个:

 某些
文本
某些
文本


TextRange )来完成该操作。 )。这可以保留换行符,如果不一定是前导空格和尾随空格。



UPDATE 2012年12月10日



然而, Selection 对象的 toString()方法是尚未标准化,并且在浏览器之间的工作不一致,所以这方法基于不稳定的基础,我现在不推荐使用。我会删除这个答案,如果它不被接受。



演示: http://jsfiddle.net/wv49v/



代码:

  function getInnerText(el){
var sel,range,innerText =;
if(typeof document.selection!=undefined&& typeof document.body.createTextRange!=undefined){
range = document.body.createTextRange();
range.moveToElementText(el);
innerText = range.text;
} else if(typeof window.getSelection!=undefined&& typeof document.createRange!=undefined){
sel = window.getSelection();
sel.selectAllChildren(el);
innerText =+ sel;
sel.removeAllRanges();
}
return innerText;
}


Basically I just need the effect of copying that HTML from browser window and pasting it in a textarea element.

For example I want this:

<p>Some</p>
<div>text<br />Some</div>
<div>text</div>

to become this:

Some
text
Some
text

解决方案

If that HTML is visible within your web page, you could do it with the user selection (or just a TextRange in IE). This does preserve line breaks, if not necessarily leading and trailing white space.

UPDATE 10 December 2012

However, the toString() method of Selection objects is not yet standardized and works inconsistently between browsers, so this approach is based on shaky ground and I don't recommend using it now. I would delete this answer if it weren't accepted.

Demo: http://jsfiddle.net/wv49v/

Code:

function getInnerText(el) {
    var sel, range, innerText = "";
    if (typeof document.selection != "undefined" && typeof document.body.createTextRange != "undefined") {
        range = document.body.createTextRange();
        range.moveToElementText(el);
        innerText = range.text;
    } else if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") {
        sel = window.getSelection();
        sel.selectAllChildren(el);
        innerText = "" + sel;
        sel.removeAllRanges();
    }
    return innerText;
}

这篇关于将HTML转换为纯文本同时保留换行符(使用JavaScript)最方便的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆