简体   繁体   English

删除 html 和 JavaScript 中的结束标签和开始标签之间的空格

[英]Remove the spaces between the closing and opening tag in html with JavaScript

I've tried all the solutions in Stackoverflow, but it doesn't really work.我已经尝试过 Stackoverflow 中的所有解决方案,但它并没有真正奏效。


Input 1: ' <ul> <li>Lorem Delor </li> </ul> '输入 1: ' <ul> <li>Lorem Delor </li> </ul> '

Expected Output 1: '<ul><li>Lorem Delor</li></ul>'预期 Output 1: '<ul><li>Lorem Delor</li></ul>'


Input 2: ' <ul> <li>Lorem <b>Ipsum</b> Delor </li> </ul> '输入 2: ' <ul> <li>Lorem <b>Ipsum</b> Delor </li> </ul> '

Expected Output 2: '<ul><li>Lorem <b>Ipsum</b> Delor</li></ul>'预期 Output 2: '<ul><li>Lorem <b>Ipsum</b> Delor</li></ul>'

Solutions in Stackoverflow: '<ul><li>Lorem<b>Ipsum</b>Delor</li></ul>' Stackoverflow 中的解决方案: '<ul><li>Lorem<b>Ipsum</b>Delor</li></ul>'


Input 3:输入 3:

   Stack

    overflow 

Expected Output 3:预期 Output 3:

   Stack

    overflow 

Many regex solutions ignore inline elements.许多正则表达式解决方案忽略内联元素。 That's why the words on the page become unified (Input 2).这就是页面上的单词变得统一的原因(输入 2)。 I wonder if there really is a clear solution to this.我想知道是否真的有一个明确的解决方案。

Important: This should only affect the html input, not the plain text.重要提示:这应该只影响 html 输入,而不是纯文本。 (Input 3) (输入 3)

You can use these two regular expressions which removes end of lines and spaces.您可以使用这两个删除行尾和空格的正则表达式。

 const input = ` <ul> <li>Lorem Delor </li> <li>Lorem Delor </li> </ul> `; const output = input // remove eols between tags.replace(/\>[\r\n ]+\</g, "><") // remove spaces between tags.replace(/(<.*?>)|\s+/g, (m, $1) => $1 || ' ').trim(); console.log(output);

In your question example you want to remove every space before end of tag but I find it unwanted.在您的问题示例中,您想删除标签结尾之前的每个空格,但我发现它不需要。 That space can be placed intentionally (it can be inline element and you might want to keep that space).可以有意放置该空间(它可以是内联元素,您可能希望保留该空间)。 So the second regular leaves one space before end tag if there was one or more spaces before.因此,如果之前有一个或多个空格,则第二个常规在结束标记之前留下一个空格。 If you really want to remove all spaces (you shouldn't) just replace ' ' with '' .如果您真的想删除所有空格(您不应该),只需将' '替换为''

Regex source 正则表达式源

use regex /\s+/gim to remove multiple spaces.使用正则表达式/\s+/gim删除多个空格。

txt.replace(/\s+/gim, ' ')

use regex />\s+</gim to remove spaces between > < .使用正则表达式/>\s+</gim删除> <之间的空格。

txt.replace(/>\s+</gim, '><')

Code:代码:

var input1 = '   <ul>   <li>Lorem Delor  </li>  </ul>  ';
var input2 = `   <ul>   <li>Lorem <b>Ipsum</b> Delor  </li>  </ul>  `;

console.log(input1.replace(/\s+/gim, ' ').trim().replace(/>\s+</gim, '><'));
console.log(input2.replace(/\s+/gim, ' ').trim().replace(/>\s+</gim, '><'));

Output: Output:

'<ul><li>Lorem Delor </li></ul>'
'<ul><li>Lorem <b>Ipsum</b> Delor </li></ul>'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM