简体   繁体   English

链接在mailto正文中被删减

[英]Link gets cut of within a body of mailto

I have a javascript code that generates emails with links in the body. 我有一个JavaScript代码,该代码生成带有正文链接的电子邮件。

Some of the links have spaces within the link, so the link gets cut of. 一些链接在链接内有空格,因此该链接被切除。

在此处输入图片说明

I tried replacing the spaces with the asacii code but it didn't work. 我尝试用asacii代码替换空格,但是没有用。

var lineBreak = "%0D%0A";

function GetMailToInfo(attachment, body) {

    attachment = attachment ? attachment.replace(" ","%0D%0A") + lineBreak + lineBreak : "";
    body += attachment + signature;
    window.location.href = "mailto:" + emailTo + "?subject=" + subject() + "&body=" + body;
}

Any idea on how to solve that? 有什么解决办法的想法吗?

Your problem is most likely because String.replace only replaces the first occurrence when using a string as the first parameter. 您的问题很可能是因为String.replace仅在将string用作第一个参数时才替换第一个匹配项。 See this MDN documentation . 请参阅此MDN文档

I would suggest either looping: 我建议要么循环:

while (attachment.indexOf(" ") >= 0) {
    attachment = attachment.replace(" ", "%0A%0D");
}

Or using RegEx to perform a pattern-based replacement. 或者使用RegEx执行基于模式的替换。

However, Quentin's solution is the proper way to go about encoding strings to be safe for URI use. 但是,Quentin的解决方案是正确编码字符串以确保URI使用安全的正确方法。 My answer here is for the more general case where it may not be a URI string. 对于更一般的情况,我的答案可能不是URI字符串。

Use encodeURIComponent to properly escape special characters in URLs: 使用encodeURIComponent可以正确转义URL中的特殊字符:

window.location.href = 
    "mailto:"   + encodeURIComponent(emailTo) + 
    "?subject=" + encodeURIComponent(subject()) + 
    "&body="    + encodeURIComponent(body);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM