使用 JavaScript 删除标签之间的所有空白

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12014441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:53:54  来源:igfitidea点击:

Remove every white space between tags using JavaScript

javascriptregexwhitespace

提问by Rafael Adel

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 :

我试图删除标签之间的空白,以便 childNodes 只包含那些标签节点而不是空白节点。这是我的代码:

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

这是 JS 代码:

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

But when i alert parentHTMLi get the same old string.

但是当我提醒时,parentHTML我得到了相同的旧字符串。

回答by David says reinstate Monica

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.

这是(不是,请参阅规则之后)因为字符串是不可变的,我认为,并且您将父元素的 innerHTML 设置为您之前从中检索到的完全相同的字符串。

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.

JS小提琴演示



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

关于jfriend00(下面)的评论,似乎正则表达式有问题,\n与提供的模式不匹配,在这种情况下,以下修正满足要求:

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.

JS小提琴演示

References:

参考:

回答by Adam Leggett

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-blockelements 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-spaceCSS property is used, this will not preserve your content.

  • inline-block元素之间的空白空间实际上是布局的预期或预期部分。如果此空格折叠为零字符,则元素之间的隐式空格将被删除。这可以通过更改我下面的正则表达式来替换为" ".

  • 我原来的答案已经更新在保留空白<script><style><pre>,或<textarea>标签。所有这些<pre>都是 CDATA,这意味着内容不是 HTML 并且在找到结束标记之前被解析,这意味着正则表达式是一个完整的解决方案。如果 a<pre>嵌套或使用white-spaceCSS 属性,则不会保留您的内容。

The solution:

解决方案:

    collapsed = expanded.replace(/(<(pre|script|style|textarea)[^]+?<\/)|(^|>)\s+|\s+(?=<|$)/g, "");

回答by Joeri

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

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

回答by ln2khanal

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

你能把 html 标签当作 js 中的字符串吗?我想这是可以做到的。尝试这个!

s.replace(/\s+/g, ' ');

回答by MFM

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.

我遇到这个线程是因为我正在寻找一种解决方案来消除由 HTML 源代码中的空格或换行符引起的 div 周围的间隙。

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.

在我意识到空白可能会导致这些间隙之前,我疯狂地试图摆脱它们。我想保持我的 HTML 源格式的可读性,所以压缩代码对我来说不是一个好的解决方案。即使我以这种方式处理它,它也不会修复由 Google 和其他供应商生成的 div。

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

我首先创建以下函数并在主体 onload 中调用它。

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

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

这似乎工作得很好,但不幸的是,它打破了我页脚中的 Google 搜索框。

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.

在尝试了许多正则表达式模式的变体但没有成功之后,我在http://www.regexpal.com/找到了这个正则表达式测试器。据我所知,以下模式可以满足我的需求。

( /(^|>)[ \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.

也就是说,该功能仍在打破搜索框。所以我最终将它移动到一个 jQuery 文档就绪函数中。现在它正在工作并且不会破坏搜索框。

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