Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - replace multi line breaks with single in javascript

this is some kind of variable content in javascript:

    <meta charset="utf-8">      <title>Some Meep meta, awesome</title>         <-- some comment here -->     <meta name="someMeta, yay" content="meep">  </head> 

I want to reduce the multi line breaks (unknown number) to a single line break while the rest of the formatting is still maintained. This should be done in javascript with a regex.

I have problems with the tabulator or to keep the format.

like image 373
e382df99a7950919789725ceeec126 Avatar asked Jun 09 '12 23:06

e382df99a7950919789725ceeec126


People also ask

What is $1 in replace JavaScript?

In your specific example, the $1 will be the group (^| ) which is "position of the start of string (zero-width), or a single space character". So by replacing the whole expression with that, you're basically removing the variable theClass and potentially a space after it.

Does JavaScript trim remove newline?

trim method removes any line breaks from the start and end of a string. It handles all line terminator characters (LF, CR, etc). The method also removes any leading or trailing spaces or tabs. The trim() method doesn't change the original string, it returns a new string.

How do you return a line break in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


1 Answers

Try this:

text.replace(/\n\s*\n/g, '\n'); 

This basically looks for two line breaks with only whitespace in between. And then it replaces those by a single line break. Due to the global flag g, this is repeated for every possible match.

edit:

is it possibile to leave a double line break instead of a single

Sure, simplest way would be to just look for three line breaks and replace them by two:

text.replace(/\n\s*\n\s*\n/g, '\n\n'); 

If you want to maintain the whitespace on one of the lines (for whatever reason), you could also do it like this:

text.replace(/(\n\s*?\n)\s*\n/, '$1'); 
like image 115
poke Avatar answered Sep 18 '22 21:09

poke