JavaScript字符串换行符? [英] JavaScript string newline character?
问题描述
\ n
所有平台的Javascript中的通用换行符都是?如果没有,我如何确定当前环境的字符?
Is \n
the universal newline character sequence in Javascript for all platforms? If not, how do I determine the character for the current environment?
我不是在询问HTML换行元素(< BR / >
)。我问的是JavaScript字符串中使用的换行字符序列。
I'm not asking about the HTML newline element (<BR/>
). I'm asking about the newline character sequence used within JavaScript strings.
推荐答案
我刚用这个傻傻的测试了一些浏览器一点点JavaScript:
I've just tested a few browsers using this silly bit of JavaScript:
function log_newline(msg, test_value) {
if (!test_value) {
test_value = document.getElementById('test').value;
}
console.log(msg + ': ' + (test_value.match(/\r/) ? 'CR' : '')
+ ' ' + (test_value.match(/\n/) ? 'LF' : ''));
}
log_newline('HTML source');
log_newline('JS string', "foo\nbar");
log_newline('JS template literal', `bar
baz`);
<textarea id="test" name="test">
</textarea>
Windows上的IE8和Opera 9使用 \r\\\
。我测试过的所有其他浏览器(Windows上的Safari 4和Firefox 3.5以及Linux上的Firefox 3.0)都使用
\ n
。他们都可以在设置值时处理 \ n
,但IE和Opera会将其转换回 \\\\ n
再次在内部。有一篇SitePoint文章,其中包含更多详细信息,名为 Javascript中的行结尾。
IE8 and Opera 9 on Windows use \r\n
. All the other browsers I tested (Safari 4 and Firefox 3.5 on Windows, and Firefox 3.0 on Linux) use \n
. They can all handle \n
just fine when setting the value, though IE and Opera will convert that back to \r\n
again internally. There's a SitePoint article with some more details called Line endings in Javascript.
另请注意,这与HTML文件本身的实际行结尾无关( \ n
和 \\\\ n
给出相同的结果。)
Note also that this is independent of the actual line endings in the HTML file itself (both \n
and \r\n
give the same results).
提交表单时,所有浏览器都会将新行规范化为<$ URL编码中的c $ c>%0D%0A 。为了看到这一点,加载例如 data:text / html,< form>< textarea name =foo> foo%0abar< / textarea>< input type =submit>< / form>
然后按提交按钮。 (有些浏览器会阻止提交页面的加载,但您可以在控制台中看到URL编码的表单值。)
When submitting a form, all browsers canonicalize newlines to %0D%0A
in URL encoding. To see that, load e.g. data:text/html,<form><textarea name="foo">foo%0abar</textarea><input type="submit"></form>
and press the submit button. (Some browsers block the load of the submitted page, but you can see the URL-encoded form values in the console.)
我认为你真的不需要尽管如此,做了很多决定。如果您只想在换行符上拆分文本,可以执行以下操作:
I don't think you really need to do much of any determining, though. If you just want to split the text on newlines, you could do something like this:
lines = foo.value.split(/\r\n|\r|\n/g);
这篇关于JavaScript字符串换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!