Javascript 用“\r\n”替换换行符 ASCII (13) 的所有实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9745874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Replacing All Instances of New Line Character ASCII (13) with "\r\n"?
提问by christian
How can I replace all instances of a newline character ASCII code (13) in a string with "\r\n"?
如何用 "\r\n" 替换字符串中换行符 ASCII 代码 (13) 的所有实例?
Any help would be appreciated.
任何帮助,将不胜感激。
回答by alex
You can use this to do it...
你可以用它来做...
str = str.replace(new RegExp(String.fromCharCode(13), 'g'), '\r\n');
Naturally, if you don't need to pass a variable to get the char code (or if it's not clearer), use the character in a regex literal, e.g. /\r/g
.
当然,如果您不需要传递变量来获取字符代码(或者如果它不清晰),请在正则表达式文字中使用该字符,例如/\r/g
.
回答by Andrew Clark
ASCII code 13 is not a newline character, it is a carriage return which in many programming languages (including JavaScript) can be represented in strings with \r
.
ASCII 码 13 不是换行符,它是一个回车符,在许多编程语言(包括 JavaScript)中可以用\r
.
Here is how you can replace all occurences of \r
in a string with \r\n
:
以下是如何用 替换\r
字符串中所有出现的\r\n
:
str = str.replace(/\r/g, "\r\n");