I created the following link generator for WhatsApp messages.
If someone writes a message with spaces, I would like them to be replaced with + in order for the link not to break if someone sends it as a plain message.
So for example, if the message is ‘This is a test’, the URL should be ‘…?text=this+is+a+test’
How can that be done with jQuery?
HTML Code
<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>
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");
}
});
3
Answers
You should use the
string.replace
function.I think is enough if you replace with spaces in the function, it will return the link in the correct form
Read more on w3Schools
Use regex replace.
output
Just use
to replace all spaces with
+
. Full code: