Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  15] [ 1]  / answers: 1 / hits: 22862  / 9 Years ago, tue, april 28, 2015, 12:00:00

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.



Conversion from plain to RTF



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



Conversion from RTF to plain



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)


More From » rtf

 Answers
9

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



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, \parn);
return {\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}n\viewkind4\uc1\pard\f0\fs17 + plain + \parn};
}

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 both in action


[#66851] Monday, April 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;