user970503
user970503

Reputation: 173

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.

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

Answers (3)

vks
vks

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

sp00m
sp00m

Reputation: 48807

This simple one should suit your needs: /[\r\n ]{2,}/g. Replace by a space.

Upvotes: 0

streetturtle
streetturtle

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

Related Questions