2

I have one html document which contains whitespaces in some nodes. For example,

<B>This is          Whitespace      Node </B>

When this html is displayed in the browser, more than one continuous space in html is always displayed as one space. To avoid this issue, I want to replace the continuous spaces with a single space and multiple &nbsp; elements.

What is the best solution to achive this?

I am using C# 2005.

2
  • Just a note: if you didn't have the opening and closing <b> tags, you could use HttpServerUtility().HtmlEncode().
    – 3Dave
    Sep 22, 2011 at 14:38
  • Suggestion: always close your HTML Entities with the ending semicolon: &nbsp;
    – ANeves
    Sep 22, 2011 at 14:43

4 Answers 4

2

Try this,

string str = "<B>This is          Whitespace      Node </B>";
Regex rgx = new Regex("([\\S][ ])");
string result = rgx.Replace(str, "$1.")
                        .Replace(" .","?")
                        .Replace(" ","&nbsp")
                        .Replace("?"," ");
0
1

Use CSS's white-space property as per http://www.w3.org/TR/CSS2/text.html#white-space-prop

white-space: pre-wrap

Or, if you really want to do it with bruteforce, replace two consecutive spaces with a non-breaking-space and a normal space... I strongly recommend against this.

string text = originalText.Replace("  ", "&nbsp; ");
0

You can try

String.Replace("  ", " ")

if you prefer regex

Regex rgx = new Regex("([ \t]|&nsbp)+");
string result = rgx.Replace(input, " ");
0

I assume you are setting the value of the control from code behind? If so then ...

<strong><asp:Literal id="myLiteral">This is          Whitespace      Node </asp:Literal></strong>

And in code behind ...

var myText = "This is          Whitespace      Node ";
myLiteral.Text = myText.Replace(" ", "&nbsp;");

If no code behind or not in a literal ...

<strong><%= "This is          Whitespace      Node ".Replace(" ", "&nbsp;") %></strong>
1
  • Also the <B> tag is deprecated ... use <strong>
    – iDevForFun
    Sep 22, 2011 at 14:31

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.