out.write("document.write('<a href='str'> '+str.slice(beg+1,end)+' </a>');");
Ouch, you've got four levels of string encoding here — no wonder it's confusing you. You've got a text string inside an HTML text node inside a JavaScript string literal inside an HTML <script> block inside a Java string literal.
It's really best to avoid doing stuff like this because it's so easy to get wrong. You're missing + to join str to the string inside the attribute value; if str contains a < or & you've got a problem due to the embedding in HTML (potentially causing cross-site scripting security holes); if str contains a space or quotes you've got a problem due to the embedding in an attribute value; the </ sequence is invalid HTML inside a <script> block...
Whilst you can fix this by hacking up your own string escape functions, I'd say you're better off using functions that don't involve bodging strings together:
out.write(
"var link= document.createElement('a');\n"+
"link.href= str;\n"+
"link.appendChild(document.createTextNode(str.slice(beg+1, end)));\n"+
"document.getElementById('foo').appendChild(link);\n"
);
Where foo is the element where you want the link to appear.