innerHTML and C%23 (C#) in anchor hrefs - Firefox
-
03-07-2019 - |
Question
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 />';
}
Solution
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.
OTHER TIPS
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 />';
Escape the percent itself and you should have it.
innerHTML = '<a href="Something/C%2523">C#</a><br />';
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>')