将 HTML 转换为纯文本同时保留换行符(使用 JavaScript)的最便捷方法是什么?
基本上我只需要从浏览器窗口复制 HTML 并将其粘贴到文本区域元素中的效果。
例如我想要这个:
<p>Some</p>
<div>text<br />Some</div>
<div>text</div>
变成这样:
Some
text
Some
text
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果该 HTML 在您的网页中可见,您可以通过用户选择(或 IE 中的
TextRange
)来实现。这确实保留了换行符,即使不一定是前导和尾随空格。更新 2012 年 12 月 10 日
但是,
Selection
对象的toString()
方法是 尚未标准化,并且在浏览器之间工作不一致,因此这种方法基于不稳定的基础和 < strong>我现在不建议使用它。如果不接受我会删除这个答案。演示: http://jsfiddle.net/wv49v/
代码:
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 ofSelection
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:
我试图找到一些我不久前为此编写的代码并使用过。效果很好。让我概述一下它做了什么,希望您可以复制它的行为。
您甚至可以进一步扩展它以格式化有序列表和无序列表等内容。这实际上取决于您想要走多远。
编辑
找到代码!
I tried to find some code I wrote for this a while back that I used. It worked nicely. Let me outline what it did, and hopefully you could duplicate its behavior.
You could even expand this more to format things like ordered and unordered lists. It really just depends on how far you'll want to go.
EDIT
Found the code!
我根据这个答案创建了一个函数: https://stackoverflow.com/a/42254787/3626940
I made a function based on this answer: https://stackoverflow.com/a/42254787/3626940
根据 chrmcpn 答案,我必须将基本的 HTML 电子邮件模板转换为纯文本版本,作为 的一部分在 Node.js 中构建脚本。我必须使用 JSDOM 才能使其工作,但这是我的代码:
Based on chrmcpn answer, I had to convert a basic HTML email template into a plain text version as part of a build script in node.js. I had to use JSDOM to make it work, but here's my code:
三步。
Three steps.