mckeever02
mckeever02

Reputation: 751

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?

Upvotes: 3

Views: 5550

Answers (2)

kockburn
kockburn

Reputation: 17616

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>

Upvotes: 3

Łukasz Blaszyński
Łukasz Blaszyński

Reputation: 1565

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>

Upvotes: 1

Related Questions