Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

use regex to detect if a string contains two newlines

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading