encodeURIComponent()忽略换行符

3

我正在尝试对文本框中的字符串进行编码,以便可以输出编码结果用于mailto链接。空格和特殊字符已经被正确编码,但换行符并没有被编码,它们只是被编码为一个空格。 如何编码我的换行符?

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;
        }

我也尝试过这个,但也没有成功:
str = encodeURIComponent(str).replace(/\n/g, '%0D%0A');

以下是目前的输出结果:

mailto:mckeever02@gmail.com?body=Testing%20Should%20be%20a%20line%20break%20before%20this%20sentence

请注意,换行符只是被编码为%20(空格)。有什么想法吗?
2个回答

3

换行使用%0A替换。使用value而不是innerHTML/innerText从文本区域获取文本。

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

console.log(encodeURIComponent(val));
<textarea id="ta">
First line
Second line
</textarea>


是的,.value 是有其存在的意义的。 - Salman A

1

看我的示例代码片段。我只是使用 innerHtml 从文本区读取数据,以便有新行可用,并使用简单的 encodeURIComponent。换行符转换为 %0A,空格转换为 %20

可能你的问题是使用了 innerText 而不是 innerHTML。innerText 不会保留新行。

const text = document.querySelector('textarea').innerHTML;
console.log(encodeURIComponent(text))
<textarea>
Test
aaaa
bbbb ccc
dddd
</textarea>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接