Skip to content
Advertisement

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

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?

Advertisement

Answer

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

use .replace() with the following regex, that captures the matching group and inserts it into a DIV:

const elPre = document.querySelector("pre");
elPre.innerHTML = elPre.textContent.replace(/^([^nn]+)/, "<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>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement