Convert RTF to Plain Text

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 do not want to use the library.

Convert from plain to RTF

Formatting styles and colors are not important, all that matters is that plain text converted to a valid RTF format

Convert from RTF to Regular

Again, styles are not important. They can be removed. All that is required is that the text data all remains (without losing the entered data)

+6
source share
2 answers

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

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

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 example of them as in action

+9
source

Adding an answer on Musefan for some hexadecimal characters

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

Source: https://habr.com/ru/post/986155/


All Articles