Home > Net >  Regular expression to replace double line breaks with HTML paragraphs
Regular expression to replace double line breaks with HTML paragraphs

Time:12-21

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.

CodePudding user response:

You can use split on line breaks, wrap every string in with a paragraph and join it all back into a string. This should have better performance than a regex.

const text='Lorem ipsum dolor sit amet.\n\nConsectetur adipiscing elit.\n\nNunc eros enim.'
text.split('\n\n').map(s => `<p>${s}</p>`).join('')

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

CodePudding user response:

Use indexOf

function nl2P (html) {
  var first = true;
  var idx = html.indexOf("\n\n");
  var prevIdx = 0;
  var newHTML = "";
  while (idx != -1) {
    newHTML  = "<p>"   html.substring(preIdx, newHTML)   "</p>";
    prevIdx = idx   2;
    idx = html.indexOf("\n\n", prevIdx);
  }
  newHTML  = "<p>"   html.substring(preIdx)   "</p>";
  return newHTML;
}

    function nl2P (html) {
      var first = true;
      var idx = html.indexOf("\n\n");
      var prevIdx = 0;
      var newHTML = "";
      while (idx != -1) {
        newHTML  = "<p>"   html.substring(prevIdx, idx)   "</p>";
        prevIdx = idx   2;
        idx = html.indexOf("\n\n", prevIdx);
      }
      newHTML  = "<p>"   html.substring(prevIdx)   "</p>";
      return newHTML;
    }
    
    console.log(nl2P ("hello\n\nworld"));

CodePudding user response:

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>
"
 */

CodePudding user response:

i found a simple solution:

let textArea = document.getElementById("textArea");
let v = textArea.value;

v = v.replace("", "<p>")
     .replaceAll("\\n\\n", "</p><p>")
     .replace(/(.*)/, "$1</p>")
     
textArea.innerHTML = v;
<textarea id="textArea" cols="30" rows="10">Lorem ipsum dolor sit amet.\n\nConsectetur TEST\n\n ANOTHER TEST \n\n adipiscing elit.\n\nNunc eros enim.</textarea>

  • Related