RegEx: How to remove extra white spaces / line bre

2019-07-22 23:31发布

I want to "strip" all (somewhat) unnecessary whitespaces from the HTML markup.

Obj: nodeValue

Render: render

For a nodeValue like that, this solution works perfectly well.


However, when having a non-breaking-space   the browsers renders - as we know - differently.

Obj: nodeValue

Render: enter image description here


I want to "strip" the string just like the DOM renderer does.

What is the RegEx that does the Job? Are there other pitfalls where I might cut something that is actually "needed" rendering?

NOTE: I'm operating on innerHTML, so the client can't help me...

2条回答
Explosion°爆炸
2楼-- · 2019-07-23 00:26

This replaces all two-or-more whitespaces with a single space:

myStr = myStr.replace(/\s{2,}/g,' ');

However, this will break anywhere you have a <pre> tag, or more generally anywhere that CSS white-space:pre is applied. To be valid, you'd need to getComputedStyle() on the elements in question and then only apply this transformation to the text nodes where the whitespace is not significant.

查看更多
聊天终结者
3楼-- · 2019-07-23 00:27

Replacing /\s\s+/ with " " would do the trick.

查看更多
登录 后发表回答