Javascript 如何取消显示JSON字符串化的textarea值?
我有一个textarea html元素,我想通过字符串化将其值保存到JSON文件中:Javascript 如何取消显示JSON字符串化的textarea值?,javascript,html,json,Javascript,Html,Json,我有一个textarea html元素,我想通过字符串化将其值保存到JSON文件中: document.querySelector(#按钮”).addEventListener(“单击”,()=>{ const rawText=document.querySelector(“#textarea”).value; const jsonText=JSON.stringify(rawText); log(jsonText); }); 文件 日志json字符串化 您只需删除新行即可: const r
document.querySelector(#按钮”).addEventListener(“单击”,()=>{
const rawText=document.querySelector(“#textarea”).value;
const jsonText=JSON.stringify(rawText);
log(jsonText);
});代码>
文件
日志json字符串化
您只需删除新行即可:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");;
从Eugen Sunic的答案出发,解决方案是:
const rawText = document.querySelector("#textarea").value.replace(/\n/g, "");
const jsonText = JSON.stringify(rawText).replace(/\\\\/g, "\\");
one\ntwo\tthree\\nfourfive
无效JSON
,因此您可能应该使用不同的格式来存储这些值,更合适的格式。@goto1抱歉,我指的是一个字符串:“one\ntwo\tthree\\nfourfive”仍然无效JSON
,如果您只想存储一些文本,那么为什么不将其存储在文本文件中。@goto1我将把字符串嵌套在某个JSON对象中,这只是为了演示。谢谢,这解决了第二个问题。但是如何保留用户输入的特殊字符呢?