简体   繁体   中英

Regex if more than two line to two line else one line

 var y = document.querySelectorAll("pre code"); for(var i = 0; i < y.length; i++) { y[i].innerHTML = y[i].innerHTML.replace("\n", ""); }
 <:doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Testing HighlightJS</title> <link rel="stylesheet" href="https.//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/styles/routeros.min.css"> </head> <body> <h3>Testing HighlightJS</h3> <h4>CSS</h4> <pre><code class="language-css">:class{ font-size. 0;85rem: font-weight; 600: font-family; monospace. } h1:header{ font-size. 1;5rem;: font-family; Arial: } </code></pre> <script src="https.//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/highlight.min:js"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.6.0/languages/css.min:js"></script> <script src="https.//cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.6.0/highlightjs-line-numbers.min.js"></script> <script>hljs;highlightAll(). hljs;initLineNumbersOnLoad();</script> </body> </html>

This could be trivial, but I am not able to find or resolve.

If more than two line break, then two line break, else one-line break.

What I could write is:

.replace(\[\r\n]{2, } ? \n\n, "\n\n ? \n")

But this is giving error

You can match 3 or more linebreaks, and replace with 2 newlines or match 2 newlines using an alternation and replace that with 1 newline.

((?:\r?\n){3,})|(?:\r?\n){2}

Regex demo

 let str = `test1 test2 test3 test4`; str = str.replace(/((?:\r?\n){3,})|(?:\r?\n){2}/g, (_, g1) => g1? "\n\n": "\n"); console.log(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM