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.
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.
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With