13

I'm trying to remove white space between tags so that childNodes only contain those tags nodes not the white space nodes too. Here's my code :

<li>            
    <label for="firstName"  class="mainLabel">First Name : </label>                                 
    <input type="text" name="firstName" id="firstName"/>                                    
    <span>This must be filled</span>
</li>   

And here's the JS code :

var parentHTML = firstName.parentNode.innerHTML;
parentHTML = parentHTML.replace(/>\n</g,"><");
firstName.parentNode.innerHTML = parentHTML;

But when i alert parentHTML i get the same old string.

2
  • 1
    In a regex, whitespace is not \n, it's \s.
    – jfriend00
    Aug 17, 2012 at 23:51
  • 1
    Why are you trying to remove the whitespace on the client in JavaScript on DOM nodes that are already rendered (presumably)? The browser ignores this whitespace anyway. If you want to send more compact HTML to the client you'll need alter it at the server level.
    – scunliffe
    Aug 18, 2012 at 0:03

5 Answers 5

29

It's (not, see after the rule) because strings are immutable, I think, and you're setting the innerHTML of the parent element to be the exact same string you retrieved from it earlier.

Instead, I'd suggest:

var firstname = document.getElementsByTagName('input')[0],
    parentHTML = firstname.parentNode.innerHTML,
    newHTML = parentHTML.replace(/\>\s+\</g,'');
firstname.parentNode.innerHTML = newHTML;

console.log(parentHTML, newHTML, (parentHTML == newHTML));

JS Fiddle demo.


With regards to the comment from jfriend00 (below), it seems the regular expression was the problem, the \n didn't match the supplied pattern, that being the case, the following amendment satisfies teh requirements:

var firstname = document.getElementsByTagName('input')[0],
    parentHTML = firstName.parentNode.innerHTML;
parentHTML = parentHTML.replace(/>\s+</g, "><");
firstName.parentNode.innerHTML = parentHTML;

console.log(firstname, parentHTML);​

JS Fiddle demo.

References:

3
  • There was nothing wrong with the string assignment in the OP's original JS code. Strings are immutable, but .replace() returns a new string which can be assigned to parentHTML just like the OP was doing so whatever issue the OP's code had, it was not because of string immutability.
    – jfriend00
    Aug 17, 2012 at 23:49
  • @jfriend00: ah? Well, thank you for the correction. Also, the problem? Apparently the regex pattern. I should've known to look there first, answer edited, updated and corrected. =/ Aug 17, 2012 at 23:50
  • The .replace(/>\s+</g, "><") option here seems to work in my eyes - see jsfiddle.net/Abeeee/gms6nt35 (although note, it needs a trim to remove outer spaces too) Jan 18, 2021 at 18:18
23

For most cases, I recommend removing space from:

  • Beginning of document
  • End of document
  • After > character
  • Before < character

There are two cases I can think of where this will not do what you want, and these are the same two cases that impact the less aggressive solutions above.

  • Empty space between inline-block elements is actually an intended or expected part of the layout. If this space is collapsed to zero characters, the implicit space between elements is removed. This can be avoided by changing my regex below to replace with a " ".

  • My original answer has been updated to preserve whitespace in <script>, <style>, <pre>, or <textarea> tags. All of these except <pre> are CDATA which means the content is not HTML and are parsed until the closing tag is found, which means the regex is a complete solution. If a <pre> is nested or the white-space CSS property is used, this will not preserve your content.

The solution:

    collapsed = expanded.replace(/(<(pre|script|style|textarea)[^]+?<\/\2)|(^|>)\s+|\s+(?=<|$)/g, "$1$3");
9
  • 3
    This is the only one that works. The accepted answer does not behave nicely when the string contains double quotes. Dec 3, 2016 at 21:32
  • 1
    absolutely the best answer! should be the chosen one.
    – MFAL
    Dec 14, 2016 at 6:29
  • 1
    Great answer, though it removes spaces before <a> tags as well, which is probably not intended
    – Dominic
    May 9, 2019 at 14:40
  • This works great. I was wanting to remove space before in a contenteditable element.
    – gbland777
    May 1, 2020 at 16:31
  • 1
    This also remove spaces from <strong> and <b> tags so "Some <strong>strong</strong> text" becomes "Some<strong>strong</strong>text" which is wrong @adam-leggett
    – philk
    Sep 24, 2020 at 6:43
10

only spaces:

parentHTML = parentHTML.replace( new RegExp( "\>[ ]+\<" , "g" ) , "><" ); 

new line, tabs and spaces:

parentHTML = parentHTML.replace( new RegExp( "\>[\s]+\<" , "g" ) , "><" ); 

https://regex101.com/r/sD7cT8/1

2
  • \r\n is more like it instead of \n\t
    – vsync
    Aug 31, 2015 at 10:05
  • 1
    @vsync: sounds like an opinion and does not help any question on this page.
    – Joeri
    Sep 2, 2017 at 16:29
5

Can you treat a html tag as a string in js? I guess it can be done. try this!

s.replace(/\s+/g, ' ');
2
  • 1
    Nope, that would replace also spaces like in: <span>Wanted Spaces</span>
    – Erdal G.
    Sep 1, 2016 at 8:10
  • Thank you , friend.
    – Anzil khaN
    Apr 24, 2020 at 13:07
0

I came across this thread because I was searching for a solution to eliminate gaps around divs caused by white space in HTML source, or line feeds in my case.

Before I realized that white space could cause these gaps, I was going nuts trying to get rid of them. I want to keep my HTML source formatted for readability, so compressing the code is not a good solution for me. Even if I handled it this way, it doesn't fix divs that are generated by Google and other vendors.

I started by creating the following function and calling it in body onload.

function Compress_Html() {
    //Remove whitespace between html tags to prevent gaps between divs.
    document.body.innerHTML = document.body.innerHTML.replace( /(^|>)\s+|\s+(?=<|$)/g, "$1" );
}

This seemed to work perfectly, but unfortunately, it breaks the Google search box I have in my footer.

After trying many variations of the regex pattern without success, I found this regex tester at http://www.regexpal.com/. I far as I can tell, the following pattern does what I need.

( /(^|>)[ \n\t]+/g, ">" )

That said, the function was still breaking the search box. So I ended up moving it into a jQuery document ready function. Now it's working and does not break the search box.

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
    $( document ).ready(function() {
        document.body.innerHTML = document.body.innerHTML.replace( /(^|>)[ \n\t]+/g, ">" );
    });
</script>
1
  • 1
    Please see my revised answer. You probably have a <script> tag that was being modified and your version of the regex happens to not be breaking it. Mar 3, 2017 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.