If you're document.write
ing to an HTML document, any text you output would have to be HTML-escaped:
function encodeHTML(s) { // for text content and attribute values with " delimiter
return s.split('&').join('&').split('<').join('<').split('"').join('"');
}
somedocument.write(encodeHTML(link.href));
However it would probably be easier to use DOM methods:
somedocument.write('<p id="out">x</p>');
somedocument.getElementById('out').firstChild.data= link.href;
Either way you don't have to worry about Unicode or &#...;
character references. JavaScript strings are natively Unicode. And you would only need to think about using encodeURI
if you are creating a URI from some script (eg. var uri= 'javascript:'+encodeURI(somejscode)
), which you're not here, you've already got a URI in the link. (encodeURIComponent
would also work, but for this case where you have a whole URI not just a component, encodeURI
will give simpler results.)
PS. You don't want to use the with
statement ever, if you can help it. (Or javascript:
URLs, for that matter!)
ETA. If you really need the original source with all errors intact, you would have to do like web-sniffer does and fetch the page again from the network. You might do this for the current page as long as it is the result of a GET method, using an XMLHttpRequest. For example:
var d= window.open().document, x= new XMLHttpRequest();
d.write('<body><pre>x</pre>');
d.close();
x.onreadystatechange= function() {
if (this.readyState===4)
d.body.firstChild.firstChild.data= this.responseText;
}
x.open('GET', location.href);
x.send(null);
Or, packed into a bookmarklet:
javascript:(function()%7Bvar%20d=window.open().document,x=new%20XMLHttpRequest();d.write('%3Cbody%3E%3Cpre%3Ex%3C/pre%3E');d.close();x.onreadystatechange=function()%7Bif(this.readyState===4)d.body.firstChild.firstChild.data=this.responseText%7D;x.open('GET',location.href);x.send(null)%7D)()