开发者

Replace continuous space with single space and multiple "&nbsp" elements

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 be开发者_Python百科st solution to achive this?

I am using C# 2005.


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("?"," ");


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; ");


You can try

String.Replace("  ", " ")

if you prefer regex

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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜