Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

encodeURIComponent() ignoring line breaks

I'm trying to encode a string from a textarea so I can output the encoded result for a mailto link. Spaces and special characters are encoded fine but line break aren't, they just get encoded as a space. How do I encode my line breaks?

if (id == 'subject' || id == 'body') {
            let str = output.innerText;
            str = encodeURIComponent(str);
            // str = str.replace(/\n/g, "%0A").replace(/ /g, "%20").replace(/&/g, "%26");
            output.innerText = str;
        }

I've also tried this which doesn't work either:

str = encodeURIComponent(str).replace(/\n/g, '%0D%0A');

Here's how my output currently looks:

mailto:[email protected]?body=Testing%20Should%20be%20a%20line%20break%20before%20this%20sentence

Notice that line breaks are just being encoded to %20 (space). Any ideas?

like image 986
mckeever02 Avatar asked Jan 21 '26 22:01

mckeever02


2 Answers

Line breaks are replaced with %0A. Get the text from textarea with value and not innerHTML/innerText

const ta = document.getElementById("ta");
const val = ta.value;

console.log(encodeURIComponent(val));
<textarea id="ta">
First line
Second line
</textarea>
like image 92
kemicofa ghost Avatar answered Jan 24 '26 11:01

kemicofa ghost


See my example snippet. Im just reading data from textarea using innerHtml to have new lines available and use simple encodeURIComponent. New lines are transfered to %0A and spaces to %20

Probably your problem was to use innerText instead of innerHTML. innerText not taking new lines.

const text = document.querySelector('textarea').innerHTML;
console.log(encodeURIComponent(text))
<textarea>
Test
aaaa
bbbb ccc
dddd
</textarea>
like image 32
Łukasz Blaszyński Avatar answered Jan 24 '26 11:01

Łukasz Blaszyński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!