The safest way to remove unwanted spaces

I have this HTML line which often has many spaces

Example:

<p>All     these words <br />
<strong>All</strong>   <em>these</em>   words
<pre>    All    these words</pre>
</p>

I need to remove them using JavaScript and come up with this regEx:

String.replace(/ {2,}/g, '');

Which seems to work with replacing unwanted spaces, but I want to keep spaces inside the PRE element.

Is this possible with regex?

+3
source share
2 answers

using:

String.replace(/(<pre[\s\S]*?>[\s\S]*?<\/pre>)| {2,}/ig, '$1')

tested in firefox 3

edit:

see the test page here: http://ashita.org/StackOverflow/replacetest.html

+2
source

You cannot do this with regular expressions, and it is that simple.

- . <pre> .. CSS ( ), white-space: pre?

HTML . , ? , HTML-.

+6

Source: https://habr.com/ru/post/1709903/


All Articles