7

I am currently working on a program that allows me to enter HTML source code into a RichTextBox control and removes the spaces from in between markups. The only problem is, I am not sure how I can differentiate between the spaces BETWEEN the markups and the spaces INSIDE the markups. Obviously, removing the spaces inside the markups would be bad. Any ideas as to how I can tell the difference?

Example: (before white space is removed)

<p>blahblahblah</p>                  <p>blahblahblah</p>

Example: (after white space is removed)

<p>blahblahblah</p><p>blahblahblah</p>
3
  • Which spaces are you referring to? The ones between tags, or the ones within a single tag?
    – Amber
    Nov 7, 2009 at 2:39
  • The white spaces between tags. Example: <p>blahblahblah</p> <p>blahblahblah</p> The space in between the 2 paragraphs. Nov 7, 2009 at 2:44
  • An alternate solution using Html Agility Pack
    – kuujinbo
    Apr 3, 2017 at 20:31

7 Answers 7

14

the solution in the link that Rasik sent here it's a solution for you too

Regex.Replace(html, @"\s*(<[^>]+>)\s*", "$1", RegexOptions.Singleline);

The regular take the markup as it is and the around space characters and change it with the markup.

Edit: A better solution that work for Micheal example

Regex.Replace(txtSource.Text,
            @"\s*(?<capture><(?<markUp>\w+)>.*<\/\k<markUp>>)\s*", "${capture}", RegexOptions.Singleline);

this regular expression will detect the markup tags and don't change what it's inside and remove the spaces out side. There's some other cases to look to it too. Like the markup without ending tags.

2
  • What about the following HTML: <div>This <span>is</span> a test</div>. Wouldn't the output be: <div>This<span>is</span>a test</div>, which would render as: Thisisa test ? Nov 7, 2009 at 3:38
  • Yes, actually for this test it doesn't work the regular expression should be tuned to detect the opening markup and the ending ones and it will more complicated one
    – Zied
    Nov 7, 2009 at 3:52
5

I'm using the following. Off the top of my head, it's shortcomings are not handling brackets inside HTML comments and inside CDATA. Are there any other angle brackets in HTML that don't signify tags?

public static class HtmlHelper
{
    // positive look behind for ">", one or more whitespace (non-greedy), positive lookahead for "<"
    private static readonly Regex InsignificantHtmlWhitespace = new Regex(@"(?<=>)\s+?(?=<)");

    // Known not to handle HTML comments or CDATA correctly, which we don't use.
    public static string RemoveInsignificantHtmlWhiteSpace(string html)
    {
        return InsignificantHtmlWhitespace.Replace(html, String.Empty).Trim();
    }
}
1
  • Absolutely true regex is there 🤩 Aug 10, 2019 at 9:56
1

I would be tempted to use a regex to match any whitespace between an end tag and the next begin tag. Regex pattern matching would avoid you having to write logic yourself.

1

Technically speaking, all spaces are part of some HTML element. The top-most element, i.e., the document, "owns" the spaces between separate<p>nodes in your example, for instance.

So I think you're asking if you can remove the space between nodes at the same level. In this case you'll need to keep track of the element nesting level and the previous element. For example, a series of<td>elements that occur within the same<tr>element, wherein you can detect the end of one</td>and the beginning of the next<td>element, and ignore all the whitespace in between.

You may be able to simplify the process and simply ignore any whitespace between a closing</x>tag and the next opening tag<y> (but there may be some difficulties with this approach that I can't think of off the top of my head).

1

You could attempt to use a regular expression to strip out the whitespace. However, the expression would have to be rather complex to differentiate between opening and closing tags and to handle nested tags.

Instead, you might parse the HTML input using a library like the Html Agility Pack and then rebuild the HTML string from the document model. This will not only strip out extra white space, it will also validate the HTML (even automatically correct common mistakes).

1

My solution (similar to how Linarize works in the XML Tools plug-in in Notepad ++)

   internal static class CONST
   {
      internal static Regex linarize_regex = new Regex(@"[\r\n]+[\x20\t]*", RegexOptions.CultureInvariant | RegexOptions.Compiled);
      internal static Regex tag_linarize_regex = new Regex(@"(?<tag><[^>]*?>)[\r\n]+[\x20\t]*", RegexOptions.CultureInvariant | RegexOptions.Compiled);
   }
   internal static class UTILS
   {
      internal static string linarize_html(string html)
      {
         try
            {
               html = CONST.tag_linarize_regex.Replace(html, "${tag}");
               html = CONST.linarize_regex.Replace(html, " ");
               return html;
            }
            catch (Exception)
            {
               return html;
            }
      }
   }
-1

I am not sure which Programming language you are using. But you can do as following in C# using Regular Expression.

public static string TrimSpaces(string str)
{
return System.Text.RegularExpressions.Regex.Replace(str, @"^\s+", string.Empty);
}

Also, look into another stackoverflow thread may be this will help.

Using regular expression to trim html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.