将 url 中的空格替换为代码


Replacing space in url with code

我有这个代码。

设置了它来推广我网站上的页面。

<script ... > 
document.write('<a href="mailto:?subject=my%20subject&body='+top.location.href+'">mail this link to a friend</a>'); 
</script>

但是在我的网址中,它在我的大多数广告系列中都有一个空格。这会分解我的促销电子邮件中的 URL,因此http://到第一个空格是超链接的。

如何替换上述代码中空格代码中的空格,这意味着整个链接将在电子邮件中超链接?

document.write('<a href="mailto:?subject=my%20subject&body=' + encodeURIComponent(top.location.href) + '">mail this link to a friend</a>');

您必须先对 url 进行编码,例如使用 encodeURIComponent 函数。

encodeURIComponent(top.location.href);
<script ... > 
var url2 = encodeURIComponent(top.location.href);
document.write('<a href="mailto:?subject=my%20subject&body='+url2 +'">mail this link to a      friend</a>');