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>
1

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

5 Comments

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.
I need last time of your help. I need to match the html comments too, regex '\<\!\-\-.*?\-\-\>' but I cant match the white spaces. the '<!--asdasdasd-->' is matched but the ``` <!-- asdasd asdlkasd jlaksd a --> ``` just a moment...
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 prnt.sc/wkstms
There is a link on the left you can click on. You have not explained what you want the comments to do
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: regex101.com/r/VVv141/1 thanks for your patience and help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.