Javascript javascript正则表达式中回车、换行和多个空格的匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28212542/
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
Match of carriage return, line feed and multiple space in javascript regular expression
提问by user970503
I am trying replace carriage return (\r) and newline (\n) and more than one spaces (' ' ) with single space.
我正在尝试用单个空格替换回车符 (\r) 和换行符 (\n) 以及多个空格 (' ' )。
I used \W+ which helped to achieve this but, it's replacing special characters also with space. I want to change this only replace above characters.
我使用了 \W+ 这有助于实现这一点,但是,它也用空格替换了特殊字符。我想改变这个只替换上面的字符。
Please help me with proper regular expression with replace method in javascript.
请用javascript中的替换方法帮助我使用正确的正则表达式。
采纳答案by streetturtle
This will work: /\n|\s{2,}/g
这将起作用: /\n|\s{2,}/g
var res = str.replace(/\n|\s{2,}/g, " ");
You can test it here: https://regex101.com/r/pQ8zU1/1
你可以在这里测试:https: //regex101.com/r/pQ8zU1/1
回答by vks
\s match any white space character [\r\n\t\f ]
You should use \s{2,}for this.It is made for this task.
你应该\s{2,}为此使用它。它是为这个任务而制作的。
回答by sp00m
This simple one should suit your needs: /[\r\n ]{2,}/g. Replace by a space.
这个简单的应该适合您的需求:/[\r\n ]{2,}/g. 用空格代替。

