Search code examples
javascripthtmlline-breaks

Regular expression to replace double line breaks with HTML paragraphs


I want to convert this string:

Lorem ipsum dolor sit amet.\n\nConsectetur adipiscing elit.\n\nNunc eros enim.

into HTML tags:

<p>Lorem ipsum dolor sit amet.</p><p>Consectetur adipiscing elit.</p><p>Nunc eros enim.</p>

Want to keep strings without double line breaks unchanged. Single line breaks should be ignored. There are no line breaks at the end nor beging of the string.

I am using javascript String.Replace() method.

I have tried this:

"one\n\ntwo".replace(/(.*)\n\n(.*)/, "<p>$1</p><p>$2</p>")

However this works only with exactly two paragraphs.


Solution

  • let s = `start
    keep
    
    new
    
    keep
    end`.replaceAll(
      // starts with \n\n or at start of string
      // shortest possible substring of any characters
      // ends with \n\n of at the end of string
      /(\n\n|^)([^]*?)(?=\n\n|$)/g,
      "\n<p>$2</p>\n", // \n are optional for more visible formatting
    );
    console.log(s);
    /*
    "
    <p>start
    keep</p>
    
    <p>new</p>
    
    <p>keep
    end</p>
    "
     */