gpt4 book ai didi

javascript - 如何在不同的操作系统上处理\n、\r和\r\n?

转载 作者:搜寻专家 更新时间:2023-11-01 04:34:52 25 4
gpt4 key购买 nike

在 Windows、Mac 和 Linux 上处理换行的正确方法是什么。假设我有一个简单的 web 应用程序,它有一个文本区域,我需要在每一行中进行字符串拆分。在处理文本区域的内容之前将\r\n 和\r 转换为\n 是否安全,或者我是否需要检测用户使用的操作系统并对每个操作系统应用条件语句?

示例代码

var content = $('textarea').val();
content = content.replace(/\r\n|\r|\n/gm, "\n");
content = content.split("\n");

// Do Something

content = content.join("\n");

// Update content
$('textarea').val(content);

最佳答案

不,只用 '\n' 编写代码就足够了。因为从 textarea 获取文本意味着导出到可以表示为文件或其他内容的文本形式来自 https://en.wikipedia.org/wiki/Newline

When writing to a file, device node, or socket/fifo in text mode, '\n' is transparently translated to the native newline sequence used by the system, which may be longer than one character. When reading in text mode, the native newline sequence is translated back to '\n'. In binary mode, no translation is performed, and the internal representation produced by '\n' is output directly.

这在很大程度上取决于你想用它做什么。如果你将它发送回你的服务器,那么它取决于你是否想将它作为文件导出给用户然后它是操作系统。但通常只使用 '\n' 几乎总是安全的,因为它更常见并且被普遍接受。

$(function(){
var $text = $("#text");
$text.val( $text.val() + "Hello \nThis is '\\r' a \r" + // here
"multi-line (\\r\\n) \r\n text with" + // here CRLF
" differents \n linefeeds" );
var s = $text.val().split('\n');
// notice line 3 on output, it's been feed by '\r'
// and we split only by '\n'
$text.val( s.map( (ss,n) => n + "\t" + ss ).join("\n") );
$("#wonder").on("click",function() {
$text.val( $text.val().split("\n").join("\t\\r\r") );
// var s = $text.val();
// either sending it via AJAX or
// export it to user, it's safe to go with '\n' .
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text" rows="7" cols="37"> Hey<br>there\n

</textarea> <br>
<button id="wonder">wonder</button>

关于javascript - 如何在不同的操作系统上处理\n、\r和\r\n?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49711012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com