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.
The dot matches all except newlines (\r\n). So use \s\S, which will match ALL characters.
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.
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.
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.
\s match any white space character [\r\n\t\f ]
You should use \s{2,}
for this.It is made for this task.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With