Javascript 是否可以通过 .replace 替换字符串中的所有回车?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7328145/
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-08-24 01:49:47  来源:igfitidea点击:

Is it possible to replace all carriage returns in a string via .replace?

javascriptreplace

提问by Mark

Is it possible to replace all carriage returns in a string with the .replacefunction? I've found quite a few complex functions to do it, but was wondering if it could be simplified with just a regex through .replace?

是否可以用.replace函数替换字符串中的所有回车?我发现了很多复杂的函数来完成它,但想知道是否可以通过一个正则表达式来简化它.replace

Thanks!

谢谢!

回答by RobG

Both \n (new line) and \r (carraige return) create a new line. To replace all instances of both at the same time:

\n(换行)和 \r(回车)都创建了一个新行。同时替换两者的所有实例:

s.replace(/[\n\r]/g, '');

Note that you might want to replace them with a single space rather than nothing.

请注意,您可能希望将它们替换为单个空格而不是空。

回答by David Laberge

Here how to do it

这里怎么做

str = str.replace(/\r/gm,'newChar');

By default, Javascript replace()replaces the first occurance. The way around it is to set the first parameters as a regex.

默认情况下,Javascriptreplace()替换第一次出现。解决方法是将第一个参数设置为正则表达式。