Search code examples
javascripthtmlescapingampersand

Javascript quitting on an ampersand "&"


I'm trying to use this JS to open a new email on a client machine with the page title already populated in the subject line and body, called by this link <a href="javascript:mailpage()">Email</a>

function mailpage()
{ mail_str = "mailto:?subject= " + document.title; mail_str += 
"&body=Hi, I thought you might be interested in this: " 
+ document.title; mail_str += 
". You can check out the web site at "
+ location.href; location.href = mail_str;
}

But some of my pages have an ampersand & as part of the page title, and the function chokes on that and only inserts the text before the & and not the & or anything after. (Yes, "choke" is a highly technical term.)

Is there a way to escape the & so the JS doesn't choke? The & actually appears as &#064; in the page source. Or do I need to go to a php function? Thanks.

Edit: this works: + encodeURIComponent(document.title); mail_str +=


Solution

  • encodeURIComponent(document.title)