0

I have the following problem:

var bodyHtml = 'Test7\n'
  + '<a href="www.google.com">Google</a>\n'
  + '<a href="www.google.com">Google</a>\n'
  + '<a href="www.yahoo.com">Yahoo</a>';    

var $tempHtml = $("<tempHtml/>").html(bodyHtml);

$tempHtml.find("a").each(function (index, a) {
  var url = $(a).attr("href");
  if (url === "www.google.com") {
    $(a).attr("href", "<%= track(1) %>");
  }
});

bodyHtml = $tempHtml.html();

Here is a JSBin for this. The problem that I have with this is that the JQuery .html() function replaces <% inside href tags with &lt% (escapes it). Is there any way of preventing this escaping since I need the string bodyHtml to remain unchanged?

I know how this could be done over RegEx, but this JQuery solution seems better if it could be done.

Steve
  • 9,270
  • 5
  • 47
  • 61
gpantic
  • 103
  • 3
  • 3
    Why do you want to do this? That's not a valid `href` attribute value. From the docs: *The href attribute on a and area elements must have a value **that is a valid URL*** – CodingIntrigue Jun 23 '14 at 11:42
  • You can follow this idea: http://stackoverflow.com/questions/11591174/escaping-of-attribute-values-using-jquery-attr but it WILL NOT work for `href` for the perfectly valid reason that @RGraham mentioned above. What are you trying to do? Maybe there is a totally different solution... – Tallmaris Jun 23 '14 at 11:46
  • 1
    Is `<%= track(1) %>` intended to be JSP? – sp00m Jun 23 '14 at 11:48
  • This pattern with <%= track(1) %> is known as EJS template and in this case it will be used for tracking clicks on this link (will be replaced with some other link later in the code) – gpantic Jun 23 '14 at 11:48

0 Answers0