简体   繁体   English

在javascript正则表达式中匹配回车,换行和多个空格

[英]Match of carriage return, line feed and multiple space in javascript regular expression

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. 我使用了\\ W +来帮助实现这个目标,但它也在用空格替换特殊字符。 I want to change this only replace above characters. 我想改变它只替换上面的字符。

Please help me with proper regular expression with replace method in javascript. 请使用javascript中的replace方法帮助我使用正确的正则表达式。

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

\s match any white space character [\r\n\t\f ]

您应该使用\\s{2,}来实现此任务。

This simple one should suit your needs: /[\\r\\n ]{2,}/g . 这个简单的应该适合您的需要: /[\\r\\n ]{2,}/g Replace by a space. 用空格代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM