Skip to content

Instantly share code, notes, and snippets.

@1-Felix
Last active December 17, 2019 08:49
Show Gist options
  • Save 1-Felix/38322d7e0deb2458aaed0dc29501b58e to your computer and use it in GitHub Desktop.
Save 1-Felix/38322d7e0deb2458aaed0dc29501b58e to your computer and use it in GitHub Desktop.
Transform every <br> inside paragraph to \n and remove every other <br>
const str = `<br><h1>Test test test</h1><br><br><p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. <br>HIER IST DER BREAK Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p><br><p>Test <br> test test test</p>`;
const regex = /(<p>(?:.|\n)+?)(?:(<br(?: | \/|\/)?>)(?:\b|\n\b| \b))((?:.|\n)+?<\/p>)/gi
//change every <br> inside paragraph into \n
// (?: ) -> Non caputuring groups (I only neeed 3 groups: befor <br>, <br> and after <br>)
// <p> -> start matching
// (?:.|\n)+?) -> matches every charater or line break (if a <br> already got removed) before <br>
// +? lazy quantifier matches as few as possible (beginning from start
// (<br(?: | \/|\/)?>) -> (2nd Group) match every <br>, <br >, <br/> <br />
// (?:\b|\n\b| \b) -> match only <br> if followed by a word, new line and a word or space and a word
// ((?:.|\n)+?<\/p>) -> (3rd Group) Match every character and linebreak between <br> and </p>
while(regex.test(htmlCell)){
str = str.replace(regex, "$1\n$3")
}
str = str.replace(/<br( \/|\/)?>/gi, "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment