admin管理员组

文章数量:1201403

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.

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.

Share Improve this question asked Jan 29, 2015 at 10:37 user970503user970503 1731 gold badge1 silver badge10 bronze badges 2
  • My sample data can be like this. A B C D\rE\r\n F – user970503 Commented Jan 29, 2015 at 10:42
  • Is it \r AND \n AND more than one space, or \r OR \n OR more than one space, because your question asks for the first but anubhava has provided the regex for the second. – Andy Commented Jan 29, 2015 at 10:42
Add a comment  | 

3 Answers 3

Reset to default 8

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

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

You should use \s{2,} for this.It is made for this task.

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

本文标签: