This is my code to share the content of a web page on WhatsApp with jquery. but inside divblock3 there is text with line breaks <br />
<div class='divblock3'><p><p>Lorem Ipsum is simply dummy .<br /> <br /> Lorem Ipsum is simply dummy textntly.<br /> <br /> Lorem Ipsum is simply dummy textntly.
whatsapp does not interpret as a line break...
any idea how to replace the <br />
with a "
"
, so that whatsapp interprets them as line breaks
<script type="text/javascript">
(function clickMe() {
const button = document.getElementById("button");
var divblock1 = $('.divblock1').text();
var divblock2 = $('.divblock2').text();
var divblock3 = $('.divblock3').text();
var message = encodeURIComponent(divblock1) "
" encodeURIComponent(divblock2) "
" encodeURIComponent(divblock3);
button.addEventListener("click", event => {
// Whatsapp Message on Button Click
window.open("https://api.whatsapp.com/send?text=" message)
});
})();
</script>
CodePudding user response:
JQuery's replace
function can search for all instances of <br>
and replaces it with the value you specify. Also Jquery's .text()
function removes all HTMLtags, but you want to keep those because you want to replace <br>
with
. So lets use the function .html()
instead.
And I would recommand that you remove the /
in <br />
it isn't necessary and will cause problems otherwise with the new code.
Small HTML edit like
<div class='divblock3'>
Lorem Ipsum is simply dummy .<br> <br> Lorem Ipsum is simply dummy textntly.<br> <br> Lorem Ipsum is simply dummy textntly.
</div>
New lines in JS
var divblock3 = $('.divblock3').html();
divblock3 = divblock3.replace(/<br>/g, '\n');
divblock3 = $('<div></div>').html(divblock3);
divblock3 = divblock3.text();
Updated example script
(At first I didn't account for the encodeURIComponent later on, it's fixed in this update by using \n
instead of
)
function clickMe() {
const button = document.getElementById("button");
var divblock1 = $('.divblock1').text();
var divblock2 = $('.divblock2').text();
// the new lines
var divblock3 = $('.divblock3').html();
divblock3 = divblock3.replace(/<br>/g, '\n');
divblock3 = $('<div></div>').html(divblock3);
divblock3 = divblock3.text();
var message = encodeURIComponent(divblock1) "
" encodeURIComponent(divblock2) "
" encodeURIComponent(divblock3);
window.open("https://api.whatsapp.com/send?text=" message, '_blank');
// and for debugging purposes you can copy this:
console.log("https://api.whatsapp.com/send?text=" message);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='divblock1'>
Subject: Strange text editor
</div>
<div class='divblock2'>
Department: IT
</div>
<div class='divblock3'>
Message: Every time I type somehting it turns to:<br><br>
Lorem Ipsum is simply dummy .<br> <br> Lorem Ipsum is simply dummy textntly.<br> <br> Lorem Ipsum is simply dummy textntly
</div>
<button onclick="clickMe()">
Send message
</button>