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?
2 Answers
Reset to default 3Line 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
版权声明:本文标题:javascript - encodeURIComponent() ignoring line breaks - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745246372a2649575.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论