Home > database >  use regex to detect if a string contains two newlines
use regex to detect if a string contains two newlines

Time:12-29

I have some text in a html page which is generated from a mysql query and it includes newlines. Im able to show the newlines in the HTML by using the <pre> tag. This enables the text to show each paragraph without need to use <p> tags.

Now I would like to programmatically (using javascript) emphasise the first paragraph by placing an outline around it. In order to to so I would need to place the first paragraph in a <div>.

I can obtain the string of the text by

var preElement = document.querySelector("pre");
var text = preElement.innerHTML;

How can I use regex to detect the first paragraph where there are two newlines so that I can place it inside <div> elements?

CodePudding user response:

Not sure (since missing in the question) what the input and desired output are, but

you could use simply use .replace() like:

const elPre = document.querySelector("pre");
elPre.innerHTML = elPre.textContent.replace(/^([^\n\n] )/, "<div>$1</div>");
pre div { background: gold; padding: 1rem; }
<pre id="test">Lorem ipsum dolor sit amet

consectetur adipisicing elit. Reprehenderit ullam vitae, quisquam molestias.

Fugit eaque officiis aspernatur voluptatum, rem quod minus temporibus
inventore obcaecati repellat nostrum tenetur blanditiis veniam.</pre>

Alternatively, here's an example using split and join

const elPre = document.querySelector("pre");

const [title, ...rest] = elPre.textContent.split("\n");
elPre.innerHTML = `<div>${title}</div>${rest.join("\n")}`;
pre div { background: gold; padding: 1rem; }
<pre id="test">Lorem ipsum dolor sit amet

consectetur adipisicing elit. Reprehenderit ullam vitae, quisquam molestias.

Fugit eaque officiis aspernatur voluptatum, rem quod minus temporibus
inventore obcaecati repellat nostrum tenetur blanditiis veniam.</pre>

CodePudding user response:

You don't need regex for this - you can simply replace the newlines with your closing </div> tag. That said, I think this is a pretty weird approach to page layout and I doubt it's really what you should be doing.

var preElement = document.querySelector("pre");
var html = '<div>'   preElement.innerHTML.replace("\n\n", "</div>");
preElement.innerHTML = html;
div {
  border: 1px solid #ccc;
  padding: 5px;
  background: #ddd;
}
<pre>Sed ut perspiciatis unde omnis

iste natus error sit voluptatem accusantium doloremque laudantium
</pre>

  • Related