将RTF转换为纯文本和从纯文本转换 [英] Convert RTF to and from plain text

查看:1040
本文介绍了将RTF转换为纯文本和从纯文本转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javascript将纯文本转换为RTF(RichText格式)。

I have a requirement to convert plain text to and from RTF (RichText Format) using javascript.

我正在为每次转换寻找一个函数,我就是不想使用图书馆。

I am looking for a function for each conversion, and I am not looking to use a library.

从普通版转换为RTF

格式化样式和颜色并不重要,重要的是我将纯文本转换为有效 RTF格式

The formatting styles and colours are not important, all that matters is that the plain text i converted into a valid RTF format

转换自RTF到普通

同样,样式并不重要。它们可以完成删除。所需要的只是所有文本数据仍然存在(不会丢失输入的数据)

Again, the styles are not important. They can be completed removed. All that is required is that all text data remains (no loss of entered data)

推荐答案

在这里找到了ac#answer ,这是一个很好的起点,但我需要一个Javascript解决方案。

I found a c# answer here which was a good starting point, but I needed a Javascript solution.

不能保证这些是100%可靠的,但它们似乎与我测试过的数据配合得很好。

There is no guarantee that these are 100% reliable, but they seem to work well with the data I have tested on.

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

这是一个行动的例子他们都在行动

这篇关于将RTF转换为纯文本和从纯文本转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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