You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS中如何为WhatsApp发送的消息添加换行

解决WhatsApp消息换行问题

问题出在你直接将包含\n的字符串拼接到URL中,WhatsApp的URL Scheme无法识别未编码的换行符。需要对消息内容进行URL编码,换行符\n对应的URL编码是%0A,通过encodeURIComponent()方法可以自动完成这个转换。

修改后的函数代码:

export function sendWhatsApp(phone='', msg='') {
  let phoneWithCountryCode = `62${ltrim(phone, '0')}`; // 628123456789
  let mobile = `+${phoneWithCountryCode}`;
  // 对消息内容进行URL编码
  let encodedMsg = encodeURIComponent(msg);
  let url = `whatsapp://send?phone=${mobile}&text=${encodedMsg}`;

  Linking.openURL(url).then((data) => {
    console.log('WhatsApp Opened');
  }).catch(() => {
    alert('Please make sure WhatsApp installed on your device');
  });
}
// end export function sendWhatsApp

函数调用方式不需要修改,依然可以用\n来表示换行:

let msg = `Hello \nThis is first line of message \nthis is the second line`;
sendWhatsApp('8123456789', msg);

这样处理后,WhatsApp就能正确识别换行符,消息会按预期分行显示。

内容的提问来源于stack exchange,提问作者dapidmini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:03:21