0
votes

I have the following output :

(a lot of new lines here)

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum has been the industry's standard dummy

text ever since the 1500s, when an unknown printer took

a galley of type and scrambled it to make a type specimen book.

(a lot of new lines here)

It has survived not only five centuries,

but also the leap into electronic typesetting,

remaining essentially unchanged. It was popularised

in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,

To clean this up i am using a lot of regex

var body = contentDiv.replace(/ {2,}/g, ' ').replace(/([^\r\n][^\n])(?:\r?\n)([^\r\n][^\n])/g,"$1$2");
$('eBody').value = body.replace(/\n{3,}/g, '\n').replace(/^\s\s*/, '');

Where contentDiv is the text above and is returned by a getElementsByTagName.

var contentDiv = element.getElementsByTagName("div")[0].textContent;

It is just that the div has a lot of formatting ( ...), that when i call the textContent function, I do get the text with spaces and extra new lines, normally it should look like:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages,

2
Is your regex not working, or you're just looking for an alternative?MDEV
yes I am just looking for an alternative, cuz i didnt like the replace replace there :/MNS
You could combine the space and newline removal with something like: .replace(/\s*(\r?\n){2,}\s*/g,"$1$1"); if that's what you're after?MDEV
Yeah that is what i wanna do :), i will try it thanks a lotMNS

2 Answers

2
votes

Single regex replace for removing leading and trailing whitespaces, as well as limiting the amount of consecutive newlines:

str = str.replace(/(\s*((\r?\n){2,})\s*|\s*((\r?\n){1,2})\s*)/g,"$2$4");

Turns:

asdfasdf 


asdfafd
 sdf  
d
d sa  






 sadfdsaf

Into:

asdfasdf

asdfafd
sdf
d
d sa

sadfdsaf

Just fix 3+ multiple newlines

.replace(/(\r?\n){3,}/g,"$1$1");

Just fix leading and trailing whitespaces

.replace(/^ *| *$/gm,'');

Update: first expression didn't clear spaces at beginning and end of string

Now does everything!

.replace(/^\s*|\s*$|(\s*((\r?\n){2,})\s*|\s*((\r?\n){1,2})\s*)/g,"$2$4");
0
votes

Also this one works Great :)

s/^\s*(?:(\r?\n)(?:[\s^\r\n]+)(.+?))$/\1\2/gm