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

如何用jQuery将WhatsApp链接生成器中的空格替换为+

WhatsApp消息链接生成器:空格转+的jQuery实现

我做了一个WhatsApp消息链接生成器,当用户输入包含空格的消息时,希望将空格替换为+,避免链接以纯文本形式发送时失效。例如当消息为This is a test时,URL应变为https://wa.me/[手机号]?text=this+is+a+test,请问如何通过jQuery实现该功能?


原HTML代码

<div class="bodyContainer" dir="rtl"><BR>
  <CENTER>
    <form id="linkgenform">
      <p class="labletext"><label for="phonenumber"> Phone number </label></p>
      <input type="number" id="phonenumber" placeholder="Phone number" />
      <P>
      <p class="labletext">
        <label for="message">
          Message
        </label>
      </p>
      <input type="text" id="message" placeholder="Please let me know..." /><BR>
      <button dir="ltr" class="getlinkBtn"></i> Get link</button>
    </form>
    <BR>
    <div class="copylinkSection">
      <p class="labletext">
        <label for="finalLink">Your link:</label>
      </p>
      <input type="text" readonly id="finalLink" />

      <button dir="ltr" class="js-textareacopybtn2">copy</button>
    </div>
  </CENTER>
</div>

原原生JavaScript代码

const form = document.querySelector("#linkgenform");
const message = document.querySelector("#message");
const phonenumber = document.querySelector("#phonenumber");
const copylinkSection = document.querySelector(".copylinkSection");

/* add event listener to getbutton */
form.addEventListener("submit", (e) => {
  e.preventDefault();
  if (message.value != "" && phonenumber.value != "") {
    giveLink(Number(phonenumber.value), message.value);
  } else {
    alert("Please Fill the form");
  }
});

function giveLink(num, text) {
  copylinkSection.style.display = "flex";
  document.querySelector(
    "#finalLink"
  ).value = `https://wa.me/${num}?text=${text}`;
}

//copy the link function
const copyTextareaBtn = document.querySelector(".js-textareacopybtn2");

copyTextareaBtn.addEventListener("click", function (event) {
  let copyTextarea = document.querySelector("#finalLink");
  copyTextarea.focus();
  copyTextarea.select();

  try {
    let successful = document.execCommand("copy");
    let msg = successful ? "successful" : "unsuccessful";
    alert("Text Copied " + msg + "!");
  } catch (err) {
    console.log("Oops, unable to copy");
  }
});

jQuery实现方案

完整jQuery代码

确保页面已引入jQuery库,随后替换原有JS代码为以下内容:

$(document).ready(function() {
    // 表单提交事件处理
    $('#linkgenform').submit(function(e) {
        e.preventDefault();
        
        const phoneNum = $('#phonenumber').val().trim();
        const inputMsg = $('#message').val().trim();
        
        if (phoneNum && inputMsg) {
            // 全局替换所有空格为+
            const encodedMsg = inputMsg.replace(/\s/g, '+');
            const waLink = `https://wa.me/${phoneNum}?text=${encodedMsg}`;
            
            $('#finalLink').val(waLink);
            $('.copylinkSection').css('display', 'flex');
        } else {
            alert('请填写完整表单');
        }
    });

    // 复制链接功能
    $('.js-textareacopybtn2').click(function() {
        const copyTarget = $('#finalLink');
        copyTarget.focus();
        copyTarget.select();
        
        try {
            const isSuccess = document.execCommand('copy');
            const tipMsg = isSuccess ? '成功' : '失败';
            alert('文本复制' + tipMsg + '!');
        } catch (err) {
            console.log('无法复制文本');
        }
    });
});

关键实现说明

  • 空格替换逻辑:使用replace(/\s/g, '+')完成全局空格替换,\s匹配任意空白字符(包括空格、制表符等),g修饰符确保替换所有匹配项,而非只替换第一个空格
  • URL编码增强(可选):如果需要兼容更多特殊字符(如标点、非英文符号),可以改用以下编码方式,同时保留+替换空格的需求:
    const encodedMsg = encodeURIComponent(inputMsg).replace(/%20/g, '+');
    
    encodeURIComponent会对URL中不允许的特殊字符进行编码,再将编码后的%20替换为+,完全符合WhatsApp链接的格式要求
  • jQuery优势:简化了DOM选择和事件绑定代码,语法更简洁直观

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:30:41