Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript regular expression to remove all whitespace except newline?

How do I remove white spaces in a string but not new line character in JavaScript. I found a solution for C# , by using \t , but it's not supported in JavaScript.

To make it more clear, here's an example:

var s = "this\n is a\n te st" 

using regexp method I expect it to return

"this\nisa\ntest" 
like image 389
sat Avatar asked Oct 06 '10 11:10

sat


People also ask

How do I get rid of white space in regex?

The replaceAll() method accepts a string and a regular expression replaces the matched characters with the given string. To remove all the white spaces from an input string, invoke the replaceAll() method on it bypassing the above mentioned regular expression and an empty string as inputs.

Is newline a whitespace character regex?

The most common forms of whitespace you will use with regular expressions are the space (␣), the tab (\t), the new line (\n) and the carriage return (\r) (useful in Windows environments), and these special characters match each of their respective whitespaces.

Which modifier ignores white space in regex?

Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments. Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments, both inside and outside character classes.

How do you get rid of all whitespace in a string JavaScript?

Using Split() with Join() method To remove all whitespace characters from the string, use \s instead. That's all about removing all whitespace from a string in JavaScript.


2 Answers

[^\S\r\n]+ 

Not a non-whitespace char, not \r and not \n; one or more instances.

like image 118
Steven Vachon Avatar answered Oct 08 '22 08:10

Steven Vachon


This will work, even on \t.

var newstr = s.replace(/ +?/g, ''); 
like image 45
Ruel Avatar answered Oct 08 '22 08:10

Ruel