Remove every white space between tags using JavaSc

2020-02-25 10:53发布

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.

5条回答
一夜七次
2楼-- · 2020-02-25 11:25

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楼-- · 2020-02-25 11:26

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

s.replace(/\s+/g, ' ');
查看更多
姐就是有狂的资本
4楼-- · 2020-02-25 11:31

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");
查看更多
够拽才男人
5楼-- · 2020-02-25 11:38

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

查看更多
Summer. ? 凉城
6楼-- · 2020-02-25 11:49

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>
查看更多
登录 后发表回答