How to remove spaces between lines in a string using Javascript

Hi, I have a string that looks like :

string = "Hello it is a test comment

              Hello it is a test comment

             Hello it is a test comment"

NOW I want to remove the white spaces between the sentences and should look like
string = "Hello this is a test comment
              Hello this is a test comment
             Hello this is a test comment"

I used some functions that I googled but nothing seems to be working and I still have White spaces between sentences with in the string.

Thanks
VM
vmandemAsked:
Who is Participating?
 
Brad HoweConnect With a Mentor DevOps ManagerCommented:
Hi,

What you are looking for is removing carriage returns.

// Strip out all line breaks.
var strSingleLineText = strMultiLineText.replace(
// Replace out the new line character.
new RegExp( "\\n", "g" ),
 

// Put in ... so we can see a visual representation of where
// the new line characters were replaced out.
" ... " 
);
 

// Alert the new single-line text value.
alert( strSingleLineText );

http://www.bennadel.com/blog/161-Ask-Ben-Javascript-Replace-And-Multiple-Lines-Line-Breaks.htm

Cheers,
Hades666
0
 
Brad HoweConnect With a Mentor DevOps ManagerCommented:
Actually, This code removes ALL linebreaks.

To get this we may need to open replace back to back linebreaks with 2 linebreak.

//Remove all blank lines
strMultiLineText.replace(/\r\n\r\n/g, ");

Cheers,
Hades666
0
 
vmandemAuthor Commented:
Hades666

Your first code did removed the spaces but all are appearing in the same line rather line by line

Like string =  "Hello this is a test comment Hello this is a test comment Hello this is a test comment"

but I want
string = "Hello this is a test comment
              Hello this is a test comment
             Hello this is a test comment"

YOUR SECOND SOLUTION DID NOT REMOVE THE SPACES AND I STILL GET THE SAME WHITE SPACES.

Thanks

0
 
vmandemAuthor Commented:
Hades666

I made a small change to your first solution but I get a single space by removing "..." but does not go to new line.

// Strip out all line breaks.
var strSingleLineText = strMultiLineText.replace(
// Replace out the new line character.
new RegExp( "\\n", "g" ),
 

// Put in ... so we can see a visual representation of where
// the new line characters were replaced out.
"  " 
);
0
 
Terry WoodsIT GuruCommented:
leakim's answer in:
http://www.experts-exchange.com/Programming/Languages/Regular_Expressions/Q__26027831.html
seems to work for me.

However, it might not work if there are line feed characters. You could try:
replace(/\r?\n\s+\r?\n/g,"\n")
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.