skip to Main Content

I’m totally lost on how to write this regex. Basically what I need here is to wrap each line with a <p></p> tag and every double new line with a <p><br /></p>. So lets say I have the following string:

Hello WorldnnFoo BarnBas Baz

I need to write an output that would format it to the following:

<p>Hello World</p>
<p><br /></p>
<p>Foo Bar</p>
<p>Bas Baz</p>

Right now all I have is this but this doesn’t work. Its not wrapping single lines with <p> tags

function textToHtml(text) {
  text = text.replace(/nn/g, '<p><br /></p>');
  return text;
}
--- 
textToHtml('Hello WorldnnFoo BarnBas Baz') 
// 'Hello World<p><br /></p>Foo BarnBas Baz'

Any nudge in the right direction would be much appreciated

3

Answers


  1. function textToHtml(text) {
      const paragraphs = text.split('n');
      const formattedText = paragraphs.map((paragraph) => {
        if (paragraph === '') {
          return '<p><br /></p>';
        } else {
          return `<p>${paragraph}</p>`;
        }
      }).join('');
      return formattedText;
    }
    var res=textToHtml('Hello WorldnnFoo BarnBas Baz');
    console.log(res);
     ------
    Output:
    
    <p>Hello World</p><p><br /></p><p>Foo Bar</p><p>Bas Baz</p>
    
    Login or Signup to reply.
  2. .+ will match one or more non-newline characters, so you could wrap the lines by adding the following as the first line of your function.

    text = text.replace(/.+/g, '<p>$&</p>');
    

    $& in the replacement string represents the whole match.

    Login or Signup to reply.
  3. The regex in this code is probably not entirely correct, but you want to use what are called "capture groups" with your regex to isolate the text you want to wrap.

    function textToHtml(text) {
      const regex = /(^.+)n{1,2}/gm
      let output = ''
      text.match(regex).forEach(match => {
        output += `<p>${match}</p>n`
      })
      return output 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search