简体   繁体   中英

javascript | save textarea value with line breaks

I have a code where it saves multiple textarea values in a text file. 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. 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.

Try this:

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

Edit , try this as the 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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