Escaping & for display in mail client (mailto link)

坚强是说给别人听的谎言 提交于 2019-12-08 17:24:52

问题


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?


回答1:


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.




回答2:


You want encodeURIComponent not encodeURI.



来源:https://stackoverflow.com/questions/6545709/escaping-for-display-in-mail-client-mailto-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!