skip to Main Content

I created a simple form with a submit button, text and phone entries. When I press the send button, whatsapp web opens and when I enter it from a mobile phone, whatsapp.com opens.
I’m trying to open whatsapp’s mobile app with the text I wrote

let number = mobileNumber.replace(/[^d]/g, "");
  let url = `whatsapp://send?phone=${number}&text=${encodeURIComponent(message)}`;

and chatGPT already tell me https://wa.me/15551234567 that will work

let number = mobileNumber.replace(/[^d]/g, "");
  let url = `whatsapp://send?phone=${number}&text=${encodeURIComponent(message)}`;

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for reply. I manage to find a solution.

    const number = mobileNumber.trim().replace(/[^d]/g, "");
    

  2. WhatsApp should be opened – according to the docs at https://faq.whatsapp.com/425247423114725/ – using their https://wa.me/<number>?text=<text> URL.

    The mentioned number 15551234567 is from those specific docs, just an example.

    So, try

        const number = mobileNumber.replace(/[^d]/g, "");
        const url = `https://wa.me/${number}?text=${encodeURIComponent(message)}`;
    

    Using const instead of let if you do not need to change the variable is a good practice, but is not required and not the reason the link from you didn’t work.


    You can test and verify this using the following snippet (which might only run locally and not here in stack overflow. I tested it locally.)

    <html>
      <body>
        <a href="" id="link" target="_blank">
            click to send WA message
        </a>
        <br>(might not work embedded in SO, but you see the example code and can test it locally)
        <p><code></code></p>
        <script>
            const mobileNumber = "+1-555-123456";
            const message = "Hello to WhatsApp";
            const number = mobileNumber.replace(/[^d]/g, "");
            const url = `https://wa.me/${number}?text=${encodeURIComponent(message)}`;
            document.querySelector("#link").setAttribute("href", url);
            document.querySelector("code").innerText = url;
        </script>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search