admin管理员组

文章数量:1416071

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?

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?

Share Improve this question asked Jan 16, 2019 at 11:45 mckeever02mckeever02 7512 gold badges7 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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>

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>

本文标签: javascriptencodeURIComponent() ignoring line breaksStack Overflow