JavaScript/REGEX: Replace extra whitespace with space or a new line if it contains new line

hankknight
hankknight used Ask the Experts™
on
Using JavaScript, I want to remove all duplicate whitespaces.   I want the extra whitespace to be replaced with a newline if the whitespace already contains a whitespace.  If extra whitespace does NOT contain a new line then the extra whitespace should be replaced with a single space.

The following code works in PHP:
// Thanks, TerryAtOpus, EEQ 26804837
$xyz = preg_replace("/(?=\s\s)\s*?(\n)\s*|(\s)\s+/", "$1$2", $xyz);

Open in new window


Here is an example:
var xyz = 'Hello           World\n\n\n    This       is   a test';
/// Should become:
/// 'Hello World\nThis is a test';

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
leakim971Multitechnician
Top Expert 2014

Commented:
Use : xyz.replace(/\s{2,}/g," ")
var xyz = 'Hello           World\n\n\n    This       is   a test';
xyz = xyz.replace(/\s{2,}/g," ")

Open in new window

Author

Commented:
Thanks, leakim971, however I want to preserved newline breaks.  Your code replaces newlines with a space.

Three consecutive spaces should become a single space.
Three consecutive tabs should become a single space.
Three consecutive newlines should become a single newline.
Three consecutive spaces followed by a newline should become a  single newline.

Please look at the PHP code and the example in my original post.  Thanks.






Multitechnician
Top Expert 2014
Commented:
var xyz = 'Hello           World\n\n\n    This       is   a test';
xyz = xyz.replace(/(?=\s\s)\s*?(\n)\s*|(\s)\s+/g," $1");

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial