简体   繁体   English

javascript |使用换行符保存textarea值

[英]javascript | save textarea value with line breaks

I have a code where it saves multiple textarea values in a text file. 我有一个代码,它在文本文件中保存多个textarea值。 However, it does not display the line breaks I indicated after saving it. 但是,它不会显示保存后我指示的换行符。 It only identifies the line breaks w/c are manually put within the textarea. 它只识别w / c的换行符是手动放入textarea中的。 Below is the code. 下面是代码。 Please help. 请帮忙。

<script>
    var TestVar = new Array(); 
    var i = 0;
    function save()
    {
        TestVar[i] = document.getElementById("text1").value + "\n" + document.getElementById("text2").value;
        mydoc = document.open();
        mydoc.write(TestVar);
        mydoc.execCommand("saveAs",true,"TicketID.txt");
        mydoc.close();
    }
</script>
</head>
<body>
    <form id=formtest>
        <textarea name="textarea" id="text1"></textarea>
        <textarea name="textarea" id="text2"></textarea>
        <input type="button" value="save" onclick="save()">
    </form>
</body>

text = text.replace(/\n\r?/g, '<br />');

text是来自textarea的值。

The problem stems from the fact that line breaks ( \\n ) are not the same as HTML <br /> tags. 问题源于换行符( \\n )与HTML <br />标记不同的事实。

Try this: 试试这个:

var text = document.forms[0].txt.value;
text = text.replace(/\n\r?/g, '<br />');

Edit , try this as the js: 编辑 ,尝试这个作为js:

var text = document.forms[0].txt.value;

if (text === true) { text = text.replace(/\n\r?/g, '<br />'); } 

var TestVar = new Array(i); 
var i = 0;
function save()
{
TestVar[i] = document.getElementById("text1").value + "/n" + document.getElementById("text2").value;
mydoc = document.open();
mydoc.write(TestVar);
mydoc.execCommand("saveAs",true,"TicketID.txt");
mydoc.close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM