javascript 将 RTF 与纯文本相互转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29922771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert RTF to and from plain text
提问by musefan
I have a requirement to convert plain text to and from RTF (RichText Format) using javascript.
我需要使用 javascript 将纯文本与 RTF(RichText 格式)相互转换。
I am looking for a function for each conversion, and I am not looking to use a library.
我正在为每次转换寻找一个函数,我不想使用库。
Conversion from plain to RTF
从普通格式到 RTF 格式的转换
The formatting styles and colours are not important, all that matters is that the plain text i converted into a validRTF format
格式样式和颜色并不重要,重要的是我将纯文本转换为有效的RTF 格式
Conversion from RTF to plain
从 RTF 到普通格式的转换
Again, the styles are not important. They can be completed removed. All that is required is that alltext data remains (no loss of entered data)
同样,样式并不重要。他们可以完成删除。所需要的只是保留所有文本数据(不会丢失输入的数据)
回答by musefan
I found a c# answer herewhich was a good starting point, but I needed a Javascript solution.
我在这里找到了 ac# answer,这是一个很好的起点,但我需要一个 Javascript 解决方案。
There is no guarantee that these are 100% reliable, but they seem to work well with the data I have tested on.
不能保证这些是 100% 可靠的,但它们似乎与我测试过的数据配合得很好。
function convertToRtf(plain) {
plain = plain.replace(/\n/g, "\par\n");
return "{\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}\n\viewkind4\uc1\pard\f0\fs17 " + plain + "\par\n}";
}
function convertToPlain(rtf) {
rtf = rtf.replace(/\par[d]?/g, "");
return rtf.replace(/\{\*?\[^{}]+}|[{}]|\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?/g, "").trim();
}
Here is a working exampleof them both in action
回答by Tjad Clark
Adding onto Musefan's answer for some hex characters
添加到 Musefan 对一些十六进制字符的回答
function convertToPlain(rtf) {
rtf = rtf.replace(/\par[d]?/g, "");
rtf = rtf.replace(/\{\*?\[^{}]+}|[{}]|\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?/g, "")
return rtf.replace(/\'[0-9a-zA-Z]{2}/g, "").trim();
}