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.

4
  • 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 Commented Jun 23, 2014 at 11:42
  • You can follow this idea: stackoverflow.com/questions/11591174/… 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... Commented Jun 23, 2014 at 11:46
  • 1
    Is <%= track(1) %> intended to be JSP? Commented Jun 23, 2014 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) Commented Jun 23, 2014 at 11:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.