Posted by: Dakusan
« on: August 02, 2013, 03:26:13 pm »Original post for Encoding & decoding HTML in JavaScript with jQuery can be found at https://www.castledragmire.com/Posts/Encoding_&_decoding_HTML_in_JavaScript_with_jQuery.
Originally posted on: 08/02/13
Originally posted on: 08/02/13
Here are a few functions I’ve been finding a lot of use for lately. They are basically the JavaScript equivalent for PHP’s htmlentities and html_entity_decode. These functions are useful for inserting HTML dynamically, and getting values of contentEditable fields. These functions do replace line breaks appropriately, and HTML2Text removes a trailing line break.
var TextTransformer=$('<div></div>');
function Text2HTML(T) { return TextTransformer.text(T).html().replace(/\r?\n/g, '
'); }
function HTML2Text(T) { return TextTransformer.html(ReplaceBreaks(T, "\x01br\x01")).text().replace(/\x01br\x01/g, "\n").replace(/\n$/, ''); }
function ReplaceBreaks(TheHTML, ReplaceText) { return TheHTML.replace(/<\s*br\s*\/?\s*>/g, ReplaceText || ' - '); }