0

I try to convert the html text into inline text without spaces between tags or between text inside tag but without text losing the spaces. Check the code below for more infos.

This is my html from which I want to remove the whitespaces

const html = `
 <div>
   <div>
     <span>This is a text</span>
     <div>
       Another text
     </div>
   </div>
 </div>
`;

I try to 'write' the regex below but it is wrong. I now remove the tag too. I tried different regex methods but I can't create (or understand) the regex code.

I do:

console.log(html.replace(/\>(\s+?)\</g,''))

output:

<divdivspan>This is a text</spandiv>
       Another text
     </div/div/div>

I want to:

console.log(html.replace('(regex)', ''))
output: <div><div><span>This is a text</span><div>Another text</div></div></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Dasd
  • 7
  • 4

1 Answers1

0

Not sure WHY you want to, but this works

I cut and pasted your HTML and I had to add \r and\n too

const html = `<!--aaaaa--><div>
   <div>
     <span>This is a text</span>
     <div><!-- asda asdasd asdasdasd -->
       Another text
     </div><!-- comment 
     over two lines -->
   </div>
 </div>`
 
 const noSpaceOrComments = html
   .replace(/<!--[\s\S]*?-->/gm,"") // comments
   .replace(/^(\s+)?|(\s+)?$/gm,"") // leading and trailing whitespace
   .replace(/\r|\n/g,"") // trailing newlines
 
 console.log(noSpaceOrComments)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 1
    Thanks very very much, you save me. My company use an old node html parser and have a bug when the html raw without be inline not recognize the html. I try to 'solve' the broken app before we rewrite. – Dasd Jan 11 '21 at 07:44
  • I need last time of your help. I need to match the html comments too, regex '\<\!\-\-.*?\-\-\>' but I cant match the white spaces. the '' is matched but the ``` ``` just a moment... – Dasd Jan 11 '21 at 08:24
  • Sorry the misunderstand I didnt explain right. I want to replace not match the comments and I dont want to open new thread. I dont know how to share from regex101.com just screenshot https://prnt.sc/wkstms – Dasd Jan 11 '21 at 08:33
  • There is a link on the left you can click on. You have not explained what you want the comments to do – mplungjan Jan 11 '21 at 08:43
  • So sorry, I want to create a 'method' to remove the comments, just replace with empty string. In the link above I write a regex witch need to match the comments but match on inline comments. I try to add references about whitespaces and new line but I cant understand the regex. I need read and learn more about regex some time when I have time. regex101 link: https://regex101.com/r/VVv141/1 thanks for your patience and help. – Dasd Jan 11 '21 at 09:27