Skip to content
Advertisement

Convert html raw text into inline text (remove spaces) Regex Javascript

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>

Advertisement

Answer

Not sure WHY you want to, but this works

I cut and pasted your HTML and I had to add r andn 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(/<!--[sS]*?-->/gm,"") // comments
   .replace(/^(s+)?|(s+)?$/gm,"") // leading and trailing whitespace
   .replace(/r|n/g,"") // trailing newlines
 
 console.log(noSpaceOrComments)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement