Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping & for display in mail client (mailto link)

I have a JavaScript function like so:

var strBody = encodeURI(window.location.href);
var strSubject = encodeURI(document.title);
var mailto_link = "mailto:?subject=" + encodeURI(strSubject) + "&body=" + strBody;

This code is executed on a hyperlink's onclick event, and opens the mail client (mailto://). However, the title of the page has several & symbols, but the title is only picked up until the first &. The url is always picked up.

What is the correct JavasSript to escape the & and display it in the mail client's subject line?

like image 359
gss5 Avatar asked Jul 01 '11 08:07

gss5


People also ask

What is the synonym of escaping?

Some common synonyms of escape are avoid, elude, eschew, evade, and shun. While all these words mean "to get away or keep away from something," escape stresses the fact of getting away or being passed by not necessarily through effort or by conscious intent.

What of the meaning of escape?

verb (used without object), es·caped, es·cap·ing. to slip or get away, as from confinement or restraint; gain or regain liberty: to escape from jail. to slip away from pursuit or peril; avoid capture, punishment, or any threatened evil. to issue from a confining enclosure, as a fluid.

What escape life means?

idiom. : to avoid death. She narrowly escaped with her life.

What is Escape person?

: a person who escapes.


1 Answers

var encoded_body = encodeURIComponent(window.location.href);
var encoded_subject = encodeURIComponent(document.title);
var mailto_link = "mailto:?subject=" + encoded_subject + "&body=" + encoded_body;

should do it (encodeURIComponent instead of encodeURI).

In your original code you were also incorrectly double encoding the subject (once on line 2, and then again on line 3).

I took the liberty of renaming your variables to make it clearer that they contain the encoded subject and body, as opposed to the original text.

like image 77
Daniel Cassidy Avatar answered Sep 19 '22 04:09

Daniel Cassidy