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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:41:21  来源:igfitidea点击:

Javascript Replacing All Instances of New Line Character ASCII (13) with "\r\n"?

javascriptnewlinestr-replace

提问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 \rin a string with \r\n:

以下是如何用 替换\r字符串中所有出现的\r\n

str = str.replace(/\r/g, "\r\n");