1

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.

1
  • Use the replaceAll method, and your regexp needs to have the /g modifier at the end. Commented Dec 20, 2022 at 20:45

4 Answers 4

4

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>'
1
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>
"
 */
0

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"));

0

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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.