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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:17:44  来源:igfitidea点击:

Convert RTF to and from plain text

javascriptrtf

提问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();
}