3

I have HTML coming from templates that I need to remove spaces between elements and new lines. I don't want to remove spaces that would break the HTML, so it is becoming tricky for me. So far I have the below to remove new lines, but spaces I am stuck on:

'<div id="head"></div> \n   <div id="body"></div>    <div id="foot"></div> '.replace(/(\r\n|\n|\r)/gm, '');

Is there hopefully something built into jQuery instead of a complex regex maybe to remove the spaces?

1
  • Don't know web stuff but is it possible to parse it with a dom, edit the elements, then reconstruct it? Because finding a tag can be quite complex. Its not like you can reliably use (in the case of tags) /(>)\s+|\s+(<)/. Commented Feb 20, 2014 at 17:44

1 Answer 1

8

This should work :

.replace(/^\s+|\r\n|\n|\r|(>)\s+(<)|\s+$/gm, '$1$2')

Fiddle

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

2 Comments

Don't forget to $.trim the wrapping whitespace in the original string if you're going to do it this way.
In some cases it breaks the text. For example <span>How</span> <span>are</span> <span>yuo</span> will be "Howareyuo"

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.