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.
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:
For most cases, I recommend removing space from:
>
character<
characterThere 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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With