Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 615
user970503 Avatar asked Jan 29 '15 10:01

user970503


People also ask

How do I match any character across multiple lines in a regular expression?

The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.

What is \r and \n in regex?

Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.

How do you match line breaks in regex?

If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”. Whether or not you will have line breaks in your expression depends on what you are trying to match. Line breaks can be useful “anchors” that define where some pattern occurs in relation to the beginning or end of a line.

How do you find multiple occurrences of a string in regex?

Method 1: Regex re. To get all occurrences of a pattern in a given string, you can use the regular expression method re. finditer(pattern, string) . The result is an iterable of match objects—you can retrieve the indices of the match using the match.


2 Answers

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

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

like image 168
vks Avatar answered Sep 19 '22 14:09

vks


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

like image 28
streetturtle Avatar answered Sep 19 '22 14:09

streetturtle