如何实现带换行的推特分享按钮?指定文本、URL及话题
解决Twitter推文分享的换行问题
推特的intent链接不直接识别字符串里的\n或HTML换行标签,需要使用URL编码的换行符,也就是%0A(换行)或%0D%0A(回车+换行),或者直接对文本进行URL编码来自动处理特殊字符。
方案1:手动替换换行符为URL编码
修改代码,把字符串里的换行符换成%0A即可:
const sendText = "aa %0A这是第二行内容"; const sendURL = window.location.href; window.open("https://twitter.com/intent/tweet?text=" + sendText + "&url=" + sendURL + "&hashtags=a,b");
方案2:使用encodeURIComponent自动编码(推荐)
为了避免空格、标点等其他特殊字符出现解析问题,建议用encodeURIComponent对文本和URL分别编码,它会自动把\n转换成符合要求的%0A:
const sendText = "aa \n这是第二行内容"; const sendURL = window.location.href; const encodedText = encodeURIComponent(sendText); const encodedURL = encodeURIComponent(sendURL); window.open(`https://twitter.com/intent/tweet?text=${encodedText}&url=${encodedURL}&hashtags=a,b`);
调整后,推特就能正确识别换行格式,生成多行的推文内容。
内容的提问来源于stack exchange,提问作者Ropher
相关产品推荐
相关产品推荐

