skip to Main Content

I need to check if a string contains <br> tags without any surrounding HTML tags. Is there a regex or any other method to do so?

For example I have strings like this:

Lorem ipsum<br><br><br>dolor sit amet

or

dolor sit amet<br>lorem isum

And need them to be

<p><br></p><p><br></p>

2

Answers


  1. so,as far as I see, you want to wrap your br tags with p tags, you can do that with string.replaceAll function in js, like this:

    string.replaceAll('<br>','<p> <br> </p>')
    
    
    Login or Signup to reply.
  2. Here is a safe method

    I investigated how to remove the extra BRs on the fly, but ran out of time

    const str = `Lorem ipsum<br><br><br>dolor sit amet
    
    dolor sit amet<br>lorem isum`
    const fragment = document.createElement("div");
    fragment.innerHTML = str;
    fragment.querySelectorAll("br").forEach(br => {
      const wrapper = document.createElement("p");
      br.parentNode.insertBefore(wrapper, br);
      wrapper.appendChild(br)
    })
    
    console.log(fragment.innerHTML);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search