Javascript quitting on an ampersand "&"

2.1k views Asked by At

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 +=

3

There are 3 answers

0
M-frankied On BEST ANSWER
encodeURIComponent(document.title)
0
Brad Christie On

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;
}
2
It Grunt On
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