Reputation: 17561
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 @
in the page source. Or do I need to go to a php function? Thanks.
Edit: this works: + encodeURIComponent(document.title); mail_str +=
Upvotes: 1
Views: 2149
Reputation: 3378
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;
}
Use \ as the escape character in javascript
Upvotes: -1
Reputation: 101614
You should be calling encodeURI or encodeURIComponent on those variables you're inserting within the destination. This will eliminate the foul characters and allow it to pass through.
function mailpage()
{
var subject = encodeURIComponent(document.title),
body= encodeURIComponent("Hi, I thought you might be interested in this: "
+ document.title + ". You can check out the web site at "
+ location.href;
location.href = "mailto:?subject= " +subject + "&body=" + body;
}
Upvotes: 2