我尝试将html文本转换为嵌入式文本,而标记之间或标记内的文本之间没有空格,但文本不会丢失空格。检查下面的代码以获取更多信息。
This is my html from which I want to remove the whitespaces
const html = `
<div>
<div>
<span>This is a text</span>
<div>
Another text
</div>
</div>
</div>
`;
我尝试在下面“写”正则表达式,但这是错误的。我现在也删除了标签。我尝试了不同的正则表达式方法,但无法创建(或理解)正则表达式代码。
我做:
console.log(html.replace(/\>(\s+?)\</g,''))
输出:
<divdivspan>This is a text</spandiv>
Another text
</div/div/div>
我想要:
console.log(html.replace('(regex)', ''))
output: <div><div><span>This is a text</span><div>Another text</div></div></div>
不确定为什么要这么做,但这可行
我剪切并粘贴了您的HTML,也不得不添加\ r和\ n
const html = `<!--aaaaa--><div>
<div>
<span>This is a text</span>
<div><!-- asda asdasd asdasdasd -->
Another text
</div><!-- comment
over two lines -->
</div>
</div>`
const noSpaceOrComments = html
.replace(/<!--[\s\S]*?-->/gm,"") // comments
.replace(/^(\s+)?|(\s+)?$/gm,"") // leading and trailing whitespace
.replace(/\r|\n/g,"") // trailing newlines
console.log(noSpaceOrComments)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句