0

I need to be able to encode the text of a HTML element, as well as, change double quotes within the HTML tags to single quotes.

For example:

<span style="color:#000;">He said "hello"</span>

Will become:

<span style='color:#000;'>He said &quot;hello&quot;</span>

I want for the double quotes to be gone, basically, as I am transferring the string of HTML (as above) to the value attribute of an input.

I can't simple escape all of the double quotes within the HTML as I need for it to be placed in the DOM as is.

My current method (below) only half works and I'm just not happy with it; it isn't efficient and only half works (for some reason it doesn't change some double quotes housed in a tag).

var newVal = $popup.find(".jqte_editor").html();

// replace the double quotes inside HTML tags with single quotes.
var regex = new RegExp("<([^\/].*?(?=>))", "g");
var result;
while ((result = regex.exec(newVal)) !== null) {
    var match = result[0];
    newVal = newVal.replace(match, match.replace(/"/g, "'"));
}

// replace double quotes outside of HTML tags with &quot;
regex = new RegExp(">([^\/].*?(?=<))", "g");
result = null;
while ((result = regex.exec(newVal)) !== null) {
    var match = result[0];
    newVal = newVal.replace(match, match.replace(/\"/g, "&quot;"));
}

I would like to be able to pull the HTML directly from the database and place into the DOM without parsing through Javascript to decode first.

Any and all help is much appreciated and please let me know if I'm unclear anywhere.

Link to the JSFiddle: http://jsfiddle.net/2sv5g9wu/1/

Josh-Mason
  • 319
  • 3
  • 8
  • 22
  • What is the problem you are trying to solve? (i.e., why do you need that information to be inside value attributes?) There's a saying that I just recently learned that I kind of like... it says, don't try to solve a solution, try to solve a problem. Maybe we can explore alternative solutions to the problem? Only reason I say this is because this type of parsing is notoriously evil. – Josh Beam Jun 08 '15 at 14:29
  • 2
    This sounds like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), as proper encoding and such really needn't be this complex. – James Thorpe Jun 08 '15 at 14:30
  • I need to send the HTML with POST data. I am generating the HTML with a jQuery text editor. Not really sure how else I'd send it with POST data (I don't want to use AJAX) and keep the HTML intact to display on retrieve. – Josh-Mason Jun 08 '15 at 14:51
  • @Josh-Mason Can create stacksnippets , jsfiddle http://jsfiddle.net to demonstrate ? `var html = encodeURIComponent('He said "hello"'); decodeURIComponent(html);` ? – guest271314 Jun 08 '15 at 14:52
  • See the question for a link to the fiddle – Josh-Mason Jun 08 '15 at 15:21
  • @Josh-Mason _"I need to send the HTML with POST data"_ Can include `html` , `js` where `HTML` sent as `"POST"` ? – guest271314 Jun 08 '15 at 16:26

0 Answers0