![](/img/trans.png)
[英]Append closing then opening HTML tag with Javascript/Jquery
[英]Remove the spaces between the closing and opening tag in html with JavaScript
我已经尝试过 Stackoverflow 中的所有解决方案,但它并没有真正奏效。
输入 1: ' <ul> <li>Lorem Delor </li> </ul> '
预期 Output 1: '<ul><li>Lorem Delor</li></ul>'
输入 2: ' <ul> <li>Lorem <b>Ipsum</b> Delor </li> </ul> '
预期 Output 2: '<ul><li>Lorem <b>Ipsum</b> Delor</li></ul>'
Stackoverflow 中的解决方案: '<ul><li>Lorem<b>Ipsum</b>Delor</li></ul>'
输入 3:
Stack
overflow
预期 Output 3:
Stack
overflow
许多正则表达式解决方案忽略内联元素。 这就是页面上的单词变得统一的原因(输入 2)。 我想知道是否真的有一个明确的解决方案。
重要提示:这应该只影响 html 输入,而不是纯文本。 (输入 3)
您可以使用这两个删除行尾和空格的正则表达式。
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);
在您的问题示例中,您想删除标签结尾之前的每个空格,但我发现它不需要。 可以有意放置该空间(它可以是内联元素,您可能希望保留该空间)。 因此,如果之前有一个或多个空格,则第二个常规在结束标记之前留下一个空格。 如果您真的想删除所有空格(您不应该),只需将' '
替换为''
。
使用正则表达式/\s+/gim
删除多个空格。
txt.replace(/\s+/gim, ' ')
使用正则表达式/>\s+</gim
删除> <
之间的空格。
txt.replace(/>\s+</gim, '><')
代码:
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:
'<ul><li>Lorem Delor </li></ul>'
'<ul><li>Lorem <b>Ipsum</b> Delor </li></ul>'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.