Reputation: 173
I am trying replace carriage return (\r) and newline (\n) and more than one spaces (' ' ) with single space.
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.
Please help me with proper regular expression with replace method in javascript.
Upvotes: 13
Views: 45699
Reputation: 67968
\s match any white space character [\r\n\t\f ]
You should use \s{2,}
for this.It is made for this task.
Upvotes: 7
Reputation: 48807
This simple one should suit your needs: /[\r\n ]{2,}/g
. Replace by a space.
Upvotes: 0
Reputation: 5850
This will work: /\n|\s{2,}/g
var res = str.replace(/\n|\s{2,}/g, " ");
You can test it here: https://regex101.com/r/pQ8zU1/1
Upvotes: 8