views:

905

answers:

4

If you set the innerHTML of a <div> to innerHTML = '<a href="Something/C%23">C#</a><br />';

What seems to actually get 'rendered' is:

<div>
<a href="Something/C#">C#</a><br />
</div>

What is the proper way to escape this so the link will stay "Something/C%23" ?

UPDATE:
I noticed a weird little thing here. If you use a function to build up the link. The extra %25 escaping is not needed. Weird.
ex.

function buildLink(tg, nm) {
  return '<a href="Something/' + tg + '">' + nm + '</a><br />';
}
+1  A: 

Try this:

<a href="Something/C%2523">C#</a><br />

Expand the "%" to "%25" and you get what you want. Then the "%25" is converted back to the percent character and the subsequent 23 is not reinterpreted.

Eddie
A downvote without a comment isn't very useful. If something is inaccurate, a comment would help so it can be corrected.
Eddie
A: 

Escape the percent itself and you should have it.

innerHTML = '<a href="Something/C%2523">C#</a><br />';
Chris Ballance
+2  A: 

It's worth noting that many browsers will render a link to "Something/C%23" as "Something/C#" as a "friendly" URL. Check your div using Firebug or a similar tool to make sure it's actually being set incorrectly.

If so, then you need to escape the percent sign as %25:

innerHTML = '<a href="Something/C%2523">C#</a><br />';
Ben Blank
+1. Good idea about Firebug. But even if I knew what was wrong... (which I sort of knew by clicking on the link). Firebug wouldn't help me fix right? or am I missing something? Thanks.
tyndall
No, Firebug is more of a debugging aid. It's sometimes hard to see what your JS has actually *done* to the document (as View Source doesn't reflect it), so a DOM inspector is very, very handy. Firebug just happens to be the best DOM inspector I've used.
Ben Blank
A: 

What seems to actually get 'rendered' is:

<a href="Something/C#">C#</a><br />

Nope. If you hover over the link Firefox will tell you in the status bar that the link goes to "C#", but it is lying. Actually click the link and you'll end up at "C%23" (it'll appear right in the address bar).

What is the proper way to escape this so the link will stay "Something/C%23" ?

You had it right the first time. "Something/C%2523" is encoded too much.

I noticed a weird little thing here. If you use a function to build up the link. The extra %25 escaping is not needed.

Being in a function or not won't affect it. What will affect it, and might be confusing you here, is if you are using the address bar to type in javascript: URLs as a testing mechanism. javascript: URLs are still URLs and any %-encoding in them will be undone one step before the JS interpreter gets a look at the code. If you used JS string literal escaping you would not meet this problem:

javascript:alert(document.body.innerHTML='<a href="Something/C\x2523">C#</a>')
bobince